docker安装使用zookeeper
- 虚拟机上docker拉取zookeeper镜像
docker pull zookeeper
- 查看docker-hub官方说明:https://hub.docker.com/_/zookeeper
- 启动一个zookeeper容器
docker run --name zk01 -p 2181:2181 --restart always -d zookeeper
- 查看运行的容器
docker ps
服务提供者springboot项目
- 简单的springboot项目即可,只需web-starter
- pom引入dubbo-starter和zkclient的依赖
<!-- https://mvnrepository.com/artifact/com.alibaba.boot/dubbo-spring-boot-starter -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
- 新建订票服务作为提供者,并注册到zookeeper
@Component //首先它是个spring容器bean
@Service //dubbo的注解,用于暴露服务
public class TicketServiceImpl implements TicketService{
@Override
public String getTicket() {
return "《功夫》·周星驰";
}
}
#server.port=8080
dubbo.application.name=provider-ticket
dubbo.registry.address=zookeeper://192.168.1.12:2181
dubbo.scan.base-packages=com.hwc.demo.ticket.service
服务消费者springboot项目
- 简单的springboot项目即可,只需web-starter
- pom引入dubbo-starter和zkclient的依赖
- 新建用户服务作为消费者,并引用远程服务
@Service //消费者是普通的spring-component
public class UserServiceImpl implements UserService{
@Reference //dubbo远程服务引用注解
TicketService ticketService;
@Override
public String orderTicket() {
return "预定到" + ticketService.getTicket();
}
}
server.port=8081
dubbo.application.name=consumer-user
dubbo.registry.address=zookeeper://192.168.1.12:2181
- 启动类加上
@EnableDubbo
运行项目
- 服务消费测试
@Autowired
UserService userService;
@Test
public void contextLoads() {
String rs = userService.orderTicket();
System.out.println(rs);
}
- 访问OK
- 补充
推荐将provider的service接口层和bean/dto层单独抽出,以供依赖复用。
(如果是简单的将provider的接口等复制到consumer项目中,还需要建立一致的包结构,这很繁琐,所以单独抽出有必要。)
使用dubbo-admin查看注册的服务
- 从GitHub上克隆出dubbo-admin的源码包,地址
- 进入dubbo-admin项目目录,可以看到pom文件以及springboot-maven的包结构
- 检查/修改
application.properties
配置内容(默认端口7001
,默认注册中心地址zookeeper://127.0.0.1:2181
)
server.port=7001
spring.velocity.cache=false
spring.velocity.charset=UTF-8
spring.velocity.layout-url=/templates/default.vm
spring.messages.fallback-to-system-locale=false
spring.messages.basename=i18n/message
spring.root.password=root
spring.guest.password=guest
dubbo.registry.address=zookeeper://127.0.0.1:2181
- 回到pom文件目录,命令行执行
mvn package
进行打包
- 打包完毕去
target
目录下,执行jar包:java -jar dubbo-admin-0.0.1-SNAPSHOT.jar
启动dubbo-admin的web应用
- 浏览器访问
http://localhost:7001
- 查看上面已注册的服务(提供者和消费者)
- 打完收工!
demo源码
https://gitee.com/super_he/demos/tree/master/spring-dubbo-1