使用dubbo需要一个注册中心,dubbo官方推荐使用zookeeper作为注册中心,下载并配置好zookeeper后,启动即可。
引入依赖
想要在项目中使用dubbo和zookeeper,首先需要引入他们的依赖
<!-- dubbo依赖 -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.8</version>
</dependency>
<!-- zookeeper依赖 -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>2.7.8</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
配置
引入依赖后,我们在使用zookeeper时需要知道它的地址,且需要对dubbo的注解进行扫描,所以需要在yml文件中添加配置信息。这段配置信息在消费者和提供者中都需要进行配置,提供者将服务注册到zookeeper,消费者需要到zookeeper中去找到服务进行操作。
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 ;