SpringCloud整合Dubbo
2022-09-22 22:47:18
Dubbo远程调用
官网参考文档 | 官网参考项目 | Dubbo+ZK文档
三个步骤
- 编写Interface接口
- 提供者实现Interface接口
- 消费者调用Interface接口
实际操作
项目中我们可以把编写Interface接口
这个步骤抽离成了一个单独的模块,然后提供者、消费者引入此目录。这个单独模块叫dubbo-api模块
- POM
1 | <!-- |
YML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16dubbo:
scan:
# dubbo 服务扫描基准包
base-packages: top.hopestation.service
protocol:
# dubbo 协议
name: dubbo
# dubbo 协议端口( -1 表示自增端口,从 20880 开始)
port: -1
registry:
# 挂载到 Spring Cloud 注册中心 此处需要dubbo-registry-nacos依赖包支持
address: nacos://127.0.0.1:8848
# 配置了启动时暂不扫描接口,好像失效了,暂时没查出原因
check: false
cloud:
subscribed-services: xx-user; xx-store启动类
1
2
3
4
5
6
7
8//增加此注解
public class MyUserApplication {
public static void main(String[] args) {
SpringApplication.run(DictUserApplication.class,args);
}
}api项目中增加接口,对应此步骤
1.编写Interface接口
1
2
3
4
5
6
7
8
9
10public interface UserServiceRemote {
/**
* 根据用户ID查询用户
* @param userId
* @return
*/
public Map<String,Object> findUserById(String userId);
}提供者增加接口实现类,对应此步骤
2.提供者实现Interface接口
1
2
3
4
5
6
7
8
9
public class UserServiceRemoteImpl implements UserServiceRemote {
public Map<String, Object> findUserById(String userId) {
// init user
return user;
}
}消费者调用接口,对应此步骤
3.消费者调用Interface接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class StoreController {
private UserServiceRemote userServiceRemote;
/**
* 模拟查询词典、用户数据
* @return
*/
public String findStoreAndUser(){
// userServiceRemote.findUserById 为Dubbo远程调用
Map<String, Object> userObj = userServiceRemote.findUserById("1234");
return "Store is testStore,And User is " + userObj;
}
}
测试
启动项目,访问路径:
http://localhost:8899/store/findStoreAndUser
出现以下结果则为Dubbo远程调用成功。
同时Nacos的服务列表也会出现两个服务,实际上是Dubbo的接口
建议Debug调试DubboService\DubboRefrence接口处,来观察情况