SpringCloud整合Dubbo
2022-09-22 22:47:18

Dubbo远程调用

官网参考文档 | 官网参考项目 | Dubbo+ZK文档

三个步骤

  1. 编写Interface接口
  2. 提供者实现Interface接口
  3. 消费者调用Interface接口

实际操作

项目中我们可以把编写Interface接口这个步骤抽离成了一个单独的模块,然后提供者、消费者引入此目录。这个单独模块叫dubbo-api模块

  1. POM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 
我这里为了使用DubboService\DubboRefrence注解,所以故意引入了2.7.7版本。
而没有使用 ubbo Spring Cloud Starter 因为目前这个依赖最高支持 2.7.6
旧版本需要使用与Spring同名称的Service注解,不太合适。新版已经弃用-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.7</version>
</dependency>

<!-- 为了将Dubbo接口,注册进入Nacos来进行注册与发现。也可以使用ZK -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
<version>2.7.7</version>
</dependency>
  1. YML

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    dubbo:
    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
  2. 启动类

    1
    2
    3
    4
    5
    6
    7
    8
    //增加此注解
    @EnableDubbo
    @SpringBootApplication
    public class MyUserApplication {
    public static void main(String[] args) {
    SpringApplication.run(DictUserApplication.class,args);
    }
    }
  3. api项目中增加接口,对应此步骤1.编写Interface接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public interface UserServiceRemote {
    /**
    * 根据用户ID查询用户
    * @param userId
    * @return
    */
    public Map<String,Object> findUserById(String userId);

    }

  4. 提供者增加接口实现类,对应此步骤2.提供者实现Interface接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @DubboService
    public class UserServiceRemoteImpl implements UserServiceRemote {
    @Override
    public Map<String, Object> findUserById(String userId) {
    // init user
    return user;
    }
    }

  5. 消费者调用接口,对应此步骤3.消费者调用Interface接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    @RestController
    @RequestMapping("/store")
    public class StoreController {

    @DubboReference
    private UserServiceRemote userServiceRemote;

    /**
    * 模拟查询词典、用户数据
    * @return
    */
    @GetMapping("/findStoreAndUser")
    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远程调用成功。
dubbo-test

  1. 同时Nacos的服务列表也会出现两个服务,实际上是Dubbo的接口

  2. 建议Debug调试DubboService\DubboRefrence接口处,来观察情况

Prev
2022-09-22 22:47:18
Next