Dubbo整合Springboot框架

本文使用的是alibaba的Dubbo。

Dubbo整合Springboot可以分為四步:

第一步:首先需要了解Dubbo官方給的建議,至少有三個工程:

接口工程:主要存實體bean和業務接口

服務提供者:業務接口的實現類和調用數據持久層,並將服務註冊到註冊中心

服務消費者:處理瀏覽器客戶端發送的請求和從註冊中心調用服務提供者提供的服務

上面的聽起來很拗口,我們來實現一個工程試試。

首先,創建上述的三個工程:

 這裡要注意:interface創建Maven項目就好了。其他兩個是springboot項目。

第二步:添加POM依賴

<!--alibaba的Dubbo集成springboot依賴-->
        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <version>0.10</version>
        </dependency>
    
<dependency>
<groupId>com.kunkun.springboot</groupId>
<artifactId>05-springboot-dubbo-interface</artifactId>
<version>1.0.0</version>
</dependency>

 

這邊主要有三個依賴:alibaba的dubbo集成springboot依賴和zookeeper依賴,以及我們的接口工程的依賴。

這裡的依賴在服務提供者和消費者的pom文件中都需要添加。

第三步:添加配置

服務提供者的application.properties:

#springboot的應用名稱(不能少,可以變)
spring.application.name=05-springboot-dubbo-provider
#是否是dubbo服務端(服務提供者)
spring.dubbo.server = true
#dubbo的註冊中心,如果位N/A表示不使用註冊中心
#我們使用zookeeper
spring.dubbo.registry = zookeeper://127.0.0.1:2181

服務消費者的配置:

#springboot的應用名稱(不能少,可以變)
spring.application.name=05-springboot-dubbo-consumer

#dubbo的註冊中心,如果位N/A表示不使用註冊中心
#我們使用zookeeper
spring.dubbo.registry = zookeeper://127.0.0.1:2181

第四步:寫代碼

首先,是接口項目的代碼:

 

 

@Data
public class Student implements Serializable {

    private static final long serialVersionUID = -302975163235439602L;


    private Integer id;
    private String name;
    private Integer age;

    public Student(Integer id,String name,Integer age){
        this.age = age;
        this.id = id;
        this.name = name;
    }
}
import com.kunkun.springboot.model.Student;

public interface StudentService {
    public Student getStudentById();
    
}

 

然後是服務提供者的代碼:

 

 

 

//dubbo的service
@Component  //表示我這個類是spring的一個bean
@Service(timeout = 100,retries = 1)//相當於原來用xml中<dubbo:service interface="xxx" , ref = "xxx">
public class StudentServiceImpl implements StudentService {

    @Override
    public Student getStudentById() {
        return new Student(1,"zhangsan",10);
    }
    
}

 

這邊需要注意的就是註解@Service需要使用的是dubbo的service,不可以使用spring的@Service。

最後是服務消費者的代碼:就是完成請求過來的處理

 

@RestController
public class StudentController {
    @Reference
    private StudentService studentService;

    @RequestMapping("/")
    public Object student(){
        return studentService.getStudentById();
    }
}

 

這邊需要注意的就是@AutoWired要換成@Reference

最後,需要在Application上面加上@EnableDubboConfiguration

@SpringBootApplication
@EnableDubboConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}