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);
    }

}