Pom依赖:
<!-- Dubbo Spring Boot Starter -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.3</version>
</dependency>
<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>
<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>
#当前应用名字
dubbo.application.name=provider-server
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
#扫描指定包下服务
dubbo.scan.base-packages=com.example.service.impl
编写服务:TicketServiceImpl.java
@Service //将服务发布出去,这里一定要用 dubbo包下的
//亲测 @Component 无用,不会启动客户端的 zookeeper
public class TicketServiceImpl implements ITicketService {
@Override
public String getTicket() {
return "一张票";
}
}
启动测试服务提供者是否正常
消费服务
server.port=8002
# 谁消费了服务
dubbo.application.name=cunsumer-server
# 注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
UserServiceImpl.java 将provider-server下 ITicketService 拷贝至consumer-server下(interface的目录一定要对应)
@Service //这里是spring下的
public class UserServiceImpl implements IUserService {
@Reference // dubbo包下,Pom坐标,可以定义路径相同的接口名
ITicketService ticketService;
@Override
public void buyTicket() {
String string = ticketService.getTicket();
System.out.println("买到了" + string);
}
}
测试
@SpringBootTest
class ConsumerServerApplicationTests {
@Autowired
IUserService userService;
@Test
void contextLoads() {
userService.buyTicket();
}
}
结果:
注:一定要开启 zookeeper服务,消费者引入提供者的接口类路径一定要和提供者的接口名一致,