一.导入依赖
<dependencies>
<!--zookeeper server-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.6.3</version>
<!--不剔除slf4j依赖会发生依赖冲突(与springboot的日志依赖)-->
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--curator recipes-->
<!--代替ZooKeeperClient-->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>5.2.0</version>
</dependency>
<!--dubbo-->
<!--高于此版本会发生bean相关错误 原因未知-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.9</version>
</dependency>
</dependencies>
二.代码部分
项目结构
Provider
注:在较早的dubbo版本中,@DubboService注解名为@Service,与springboot的@Service注解同名,此时一般采用@Component(springboot)+@Service(dubbo)
public interface TicketService {
String sellTicket();
}
//dubbo 服务注册与发现
@Service//spring注解
@DubboService//dubbo注解 项目启动后服务自动注册到注册中心
public class TicketServiceImpl implements TicketService{
@Override
public String sellTicket() {
return "A Ticket";
}
}
Consumer
注:此处的@Service注解为springboot注解(因为服务消费者无需被dubbo发现并注册入zookeeper)
@Service
public class UserService {
//从注册中心获取远程服务
//实际情况使用POM坐标
//此处为了简单演示效果 定义与服务者接口相同路径下的同名接口(TicketService)
@DubboReference
TicketService ticketService;
public void buyTicket(){
String ticket = ticketService.sellTicket();
System.out.println("Bought " + ticket);
}
}
public interface TicketService {
String sellTicket();
}
三.配置yml文件
Provider
server:
port: 8001
dubbo:
#dubbo应用名
application:
name: ticket-provider
#向何服务注册中心注册ַ
registry:
address: zookeeper://127.0.0.1:2181
#被注册的服务提供者的包路径
scan:
base-packages: cn.alan.Service
Consumer
server:
port: 8101
dubbo:
#dubbo应用名
application:
name: ticket-consumer
#从何服务注册中心获取服务
registry:
address: zookeeper://127.0.0.1:2181
运行效果
1.开启zkServer.cmd
2.启动Provider
3.启动Consumer
运行测试类