zookeeper版本3.6.3
一,创建一个springboot项目
二,创建consumer-server
和provider-server
provider-server服务提供者
- 将服务提供者注册到注册中心,我们需要整合Dubbo和zookeeper,所以需要导包
<!--dubbo-->
<!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo-spring-boot-starter -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.7</version>
</dependency>
<!--ZooKeeper 客户端-->
<!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
<!--ZooKeeper 服务端-->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.12.0</version>
</dependency>
<!--ZooKeeper-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.14</version>
<!--排除这个slf4j-log4j12-->
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
- 在springboot配置文件中配置dubbo相关属性
server.port=8000
spring.application.name=dubbo-demo-provider
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
#哪些服务要被注册
dubbo.scan.base-packages=com.fan.service
- 在service的实现类中配置服务注解,发布服务!注意导包问题
@Service 注解,Spring 和 Dubbo 分别有自己的,且名字一样,容易造成导错包,还不知道问题出在哪
不过在新的版本中 @Service 换成了 @DubboService
- 测试
进入 Dubbo admin 页面查看
提示:如果 zookeeper 的版本过高,会出现 Springboot 连接不上 zookeeper 的情况,可以自行解决,也可以用最省事的办法降版本
逻辑理解 :应用启动起来,dubbo就会扫描指定的包下带有@component注解的服务,将它发布在指定的注册中心中!
consumer-server服务消费者
- 导入依赖,和之前的依赖一样
- 配置参数
server.port=9000
#配置消费者去注册中心取服务,
#所以需要暴露自己的名字
dubbo.application.name=consumer-server
#注册中心的地址
dubbo.registry.address=zookeeper://localhost:2181
- 本来正常步骤是需要将服务提供者的接口打包,然后用pom文件导入
我们这里使用简单的方式,直接将服务的接口拿过来,路径必须保证正确,即和服务提供者相同
- 完善消费者的服务类
@RestController
public class HelloController {
@DubboReference
HelloService helloService;
@RequestMapping("/hello")
public String Hello(){
return helloService.sayHello("张三Hello");
}
}