1、zookeeper 安装与启动
下载
官网 https://zookeeper.apache.org/
启动zookeeper
启动前zookeeper可能还需要做些调整,可以按顺寻先执行zkServer.cmd zkCli.cmd。如果报错做以下调整
复制zoo_sample.cfg 粘贴 命名为zoo.cfg
报Error: JAVA_HOME is not set错误,在zkEnv.cmd新增JAVA_HOME的地址
set JAVA=E:\Java\jdk1.8.0_301\bin\java
启动zkServer.cmd
启动zkCli.cmd,输入 ls / 显示zookeeper表示启动成功
2、dubbo
2.1 创建provider、consumer工程
2.2 依赖 两个工程都添加一样的
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.8</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>
<!--排除日志冲突 -->
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--zkclient-->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
2.3 application.properties配置
provider
server.port=8082
# 服务应用名字
dubbo.application.name=provider-server
# 注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
# 哪些服务要被注解,开启包扫描,可替代 @EnableDubbo 注解
dubbo.scan.base-packages=com.example.service
consumer
server.port=8081
dubbo.application.name=consumer-server
dubbo.registry.address=zookeeper://127.0.0.1:2181
完整结构
TicketService 两个工程一样
package com.example.service;
public interface TicketService {
String getTicket();
}
TicketServiceImpl
package com.example.service;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;
@Service
@DubboService
public class TicketServiceImpl implements TicketService{
@Override
public String getTicket() {
return "测试获取";
}
}
consumer 获取
package com.example;
import com.example.service.TicketService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DubboConsumerApplicationTests {
// 引用,方法一:pom坐标
// 方法二:定义路径相同的路径名,比如provider中com.example.service.TestService
// consumer同样路径下创建相同class 实际应用中不会使用方法二
@DubboReference
TicketService ticketService;
@Test
void contextLoads() {
String ticket = ticketService.getTicket();
System.out.println("消费服务获取信息-----》"+ticket);
}
}
分别启动 provider consumer服务,调用provider服务中方法成功