Spring Boot 整合 Dubbo RPC

图片

一、前言

Dubbo 是一款高性能、轻量级的开源 Java RPC 框架,用于快速构建分布式服务。Spring Boot 是一个基于 Spring 的快速开发框架,可以简化项目配置和部署。本文将介绍如何在 Spring Boot 项目中整合 Dubbo RPC,实现服务提供者和服务消费者之间的通信。

二、服务提供方

2.1 添加依赖

<!--dubbo nacos-->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-registry-nacos</artifactId>
    <version>2.7.15</version>
</dependency>
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.15</version>
</dependency>

2.2 配置文件

dubbo:
  registry:
    address: nacos://${nacos.host}:${nacos.port}
  application:
    name: ${spring.application.name}

2.3 启动类开启 Dubbo

/**
 * @author hope
 * 项目启动类
 */
@EnableDubbo
@EnablePropertyFeignClients
@EnableDiscoveryClient
@EnablePropertyResourceServer
@SpringBootApplication
public class DubboApplication {
    public static void main(String[] args) {
        SpringApplication.run(DubboApplication.class, args);
    }
}

2.4 提供接口


/**
 *
 * @Author: hope
 * 
 */
public interface ErpDubboService {

   /**
   * 查询列表信息
   *
   * @return
   */
  List getList();

}

2.5 注册服务

/**
 *
 * @Author: hope
 * 
 */
@DubboService
public class ErpDubboServiceImpl implements ErpDubboService {

    @Override
	public List getList() {
		return Arrays.asList(100, 200);
	}

}

三、服务消费方

3.1 添加依赖

<!--dubbo nacos-->
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-registry-nacos</artifactId>
    <version>2.7.15</version>
</dependency>
<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-spring-boot-starter</artifactId>
    <version>2.7.15</version>
</dependency>

3.2 配置文件

dubbo:
  registry:
    address: nacos://${nacos.host}:${nacos.port}
  application:
    name: ${spring.application.name}

3.3 启动类开启 Dubbo

/**
 * @author hope
 * 项目启动类
 */
@EnableDubbo
@EnablePropertyFeignClients
@EnableDiscoveryClient
@EnablePropertyResourceServer
@SpringBootApplication
public class DubboApplication {
    public static void main(String[] args) {
        SpringApplication.run(DubboApplication.class, args);
    }
}

3.4 @DubboReference 注入

/**
 *
 * @Author: hope
 * 
 */
@Service("dubboService")
public class DubboTestServiceImpl implements DubboTestService {

  @DubboReference
  private ErpDubboService erpDubboService;
 
  
  /**
   * @Description 获取列表
   **/
  public void getList() {
      // 可以调用ErpDubboService提供的api
      List list = erpDubboService.getList();
  }
  
}

四、结语

以上就是一个基本的Spring Boot和Dubbo的整合示例。在这个示例中,我们创建了一个服务接口和一个实现类,并用@DubboService注册服务,然后在消费者中使用@DubboReference注解来引用这个服务。

图片

猜你喜欢

转载自blog.csdn.net/weixin_40381772/article/details/132814556