116186477557223935
前言
SpringBoot项目整合Dubbo
准备工作
引入依赖
1 2 3 4 5
| <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>0.2.0</version> </dependency>
|
生产者
- 生产者将本地Service提供的服务通过Dubbo发布到注册中心
- 修改配置文件,添加Dubbo配置
src/main/resources/application.yml1 2 3 4 5 6 7 8 9 10 11 12
| dubbo: scan: basePackages: com.example application: name: provider-name qos-port: 22222 registry: address: zookeeper://127.0.0.1:2181 protocol: name: dubbo port: 20880
|
- 定义Services层接口
src/main/java/com/example/service/UserService.java1
| public interface UserService {}
|
3. ServiceImpl中,将注解的依赖从org.springframeword.stereotype.Service改为Dubbo的org.apache.dubbo.config.annotation.Service(Dubbo 2.7.7以前)
3. ServiceImpl中,将注解的依赖从org.springframeword.stereotype.Service改为Dubbo的org.apache.dubbo.config.annotation.DubboService(Dubbo 2.7.7及以后)
src/main/java/com/example/service/UserServiceImpl.java1 2
| @DubboService public class UserServiceImpl {}
|
消费者
- 消费者从注册中心注入Dubbo提供的服务而不是本地Service提供的服务
- 修改配置文件,添加Dubbo配置
src/main/resources/application.yml1 2 3 4 5 6 7 8 9
| dubbo: scan: basePackages: com.example application: name: consumer-name qos-port: 22222 registry: address: zookeeper://127.0.0.1:2181
|
- 定义Services层接口
src/main/java/com/example/service/UserService.java1
| public interface UserService {}
|
Controller中,将注解@Autowired换成Dubbo的org.apache.dubbo.config.annotation.Reference注解
@Reference(loadbalance = "random"):随机算法,默认不加参数时就是随机算法
@Reference(loadbalance = "roundrobin"):轮询算法
@Reference(loadbalance = "consistenthash"):一致性hash算法
@Reference(loadbalance = "leastactive"):最少访问算法
@Reference(check = false):启动消费者时不去校验是否有生产者
因为消费者不访问数据库,所以消费者模块的启动类上标注@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)注解,标注后,不连接MyBatis也不报错
src/main/java/com/example/controller/UserController.java1 2 3 4 5
| @Controller public class UserController { @Reference UserService userService; }
|
完成