SpringBoot-13 Dubbo实战
前提: 已经准备好Dubbo-admin和Zookeeper
前置准备
1.创建项目
显示创建一个Empty Project,创建两个Module—>consumer-server以及provider-server:
这是创建成功的结构。
2.导入依赖
两个Module都导入下方依赖:
<!-- dubbo-spring-boot-starter --><dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-spring-boot-starter</artifactId><version>2.7.8</version></dependency><!-- zkclient --><dependency><groupId>com.github.sgroschupf</groupId><artifactId>zkclient</artifactId><version>0.1</version></dependency><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><dependency><groupId>org.apache.zookeeper</groupId><artiad8factId>zookeeper</artifactId><version>3.4.14</version><exclusions><exclusion><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></exclusion></exclusions></dependency>
搭建项目
1.提供者
1.1 Service层
创建一个Service文件夹:
public interface TicketService {public String getTicket();}
@Service@Componentpublic class TicketServiceImpl implements TicketService {@Overridepublic String getTicket() {return \"这是一个getTicket()\";}}
注意:
这里的@Component是Spring下的注解,但是@Service应该使用的是Dubbo下的注解
用了Dubbo尽量不要用@Service,如果要使用,记得分清楚Spring和Dubbo注解的不同
1.2 配置信息
server.port=8001# 服务应用名字dubbo.application.name=provider-server# 注册中心地址dubbo.registry.address=zookeeper://127.0.0.1:2181# 注册服务dubbo.scan.base-packages=com.zc.Service
1.3 查看Dubbo的消费者
- 打开Zookeeper的服务器
- 运行Dubbo-admin打包的jar包
java -jar xxxx.jar
- 运行消费者Module
2.消费者
2.1 Service层
@Servicepublic class UserService {//想拿到 提供者 提供的东西,要去注册中心拿@Reference //引用TicketService ticketService;public void buyTicket(){String ticket = ticketService.getTicket();System.out.println(\"拿到啦---\"+ticket);}}
-
这里的@Service是将该类注入到Spring容器,使用的Spring的注解
-
这里 TicketService ticketService; 会报错,因为在 consumer-server 中没有 TicketService 这个接口。
所以,我们把这个接口复制过来:
public interface TicketService {public String getTicket();}
这样就可以使用了,Dubbo会自动给你引用提供者的实现类。
2.2 配置信息
server.port=8002# 消费者拿服务路径dubbo.application.name=consumer-server# 注册中心的地址dubbo.registry.address=zookeeper://127.0.0.1:2181
消费者与提供者的不同:
提供者配置信息不需要注册服务,消费者提供地址,消费者只需要拿到服务。
3.运行测试
在consumer-server中的test中进行测试:
@SpringBootTestclass ConsumerServerApplicationTests {@AutowiredUserService userService;@Testvoid contextLoads() {userService.buyTicket();}}
小结
前提:Zookeeper已经开启
-
提供者提供服务
导入依赖
- 配置注册中心的地址,以及服务发现名,和要扫描的包~
- 在想要被注册的服务上面-增加一个注解@Servicel,dubbo的
消费者如何消费
- 导入依赖
个人博客为:
MoYu\’s HomePage
MoYu\’s Gitee Blog