dubbo的简单使用

慈云数据 2024-04-27 技术支持 37 0

使用dubbo需要一个注册中心,dubbo官方推荐使用zookeeper作为注册中心,下载并配置好zookeeper后,启动即可。

dubbo的简单使用
(图片来源网络,侵删)

引入依赖

想要在项目中使用dubbo和zookeeper,首先需要引入他们的依赖

      
      
        org.Apache.dubbo
        dubbo-spring-boot-starter
        2.7.8
      
 
      
      
        org.apache.dubbo
        dubbo-dependencies-zookeeper
        2.7.8
        
          
            org.slf4j
            slf4j-log4j12
          
        
      

配置

引入依赖后,我们在使用zookeeper时需要知道它的地址,且需要对dubbo的注解进行扫描,所以需要在yml文件中添加配置信息。这段配置信息在消费者和提供者中都需要进行配置,提供者将服务注册到zookeeper,消费者需要到zookeeper中去找到服务进行操作

dubbo的简单使用
(图片来源网络,侵删)
dubbo:
  registry:
    address: zookeeper://localhost:2181   # zookeeper注册中心的地址
  scan:
    base-packages: com.dhcc.dataservice.service   # 包扫描
  provider:
    timeout: 50000    # 超时时间
    retries: 2        # 重试次数

提供者

在service层的实现类上添加@DubboService注解,将该类的对象注册到注册中心和IOC容器

@DubboService(interfaceClass = LoanInfoService.class , version = "v1") // 服务提供者
public class LoanInfoServiceImpl implements LoanInfoService {

消费者

在需要使用到某个注册到zookeeper中的service时,需要在其上方添加@DubboReference注解,该注解可以获取到zookeeper中的注册的service对象,并将其放入到Spring容器。

@DubboReference(interfaceClass = LoanInfoService.class , version = "v1")
protected LoanInfoService loanInfoService ;
微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon