示例描述
订单服务做集群后将地址注册到zookeeper中,会员服务从zookeeper中获取订单服务的集群地址
示例图
图片.png示例代码
示例是在springboot项目中运行的。
1.在pom.xml文件中添加zkclient的引用
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.8</version>
</dependency>
2.配置yml文件
server:
port: 8085
jybParam:
zookAddr: 192.168.100.128:2181
timeOut: 5000
3.创建订单服务(服务注册者)AppOrderRunnerImpl
说明:实现AppOrderRunnerImpl后早springboot项目启动时将服务信息注册到zookeeper中
@Component
public class AppOrderRunnerImpl implements ApplicationRunner {
@Value("${jybParam.zookAddr}")
private String zookAddr;
@Value("${jybParam.timeOut}")
private int timeOut;
@Value("${server.port}")
private String serverPort;
private String parentPath = "jyb";
// 计数器
private static CountDownLatch countDownLatch = new CountDownLatch(1);
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("-------------------------程序开始启动---------------------------");
ZooKeeper zooKeeper = new ZooKeeper(zookAddr, timeOut, new Watcher() {
// 获取该连接是否成功
@Override
public void process(WatchedEvent watchedEvent) {
Event.KeeperState state = watchedEvent.getState();
if (state == Event.KeeperState.SyncConnected) {
System.out.println("zk连接成功");
// 计数器减去1
countDownLatch.countDown();
}
}
});
//计数器等待
countDownLatch.await();
//创建父节点
String parentPath = "/jyb-service";
//判断节点是否存在
Stat exists = zooKeeper.exists(parentPath, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
if (exists == null) {
// 父节点不存在就创建持久节点
zooKeeper.create(parentPath, "parentCatalogue".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
String path = "http://127.0.0.1:" + serverPort;
//创建临时子节点
zooKeeper.create(parentPath + "/" + serverPort, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL);
// Thread.sleep(5000);
//zooKeeper.close();
System.out.println("服务注册成功" + parentPath);
}
}
4.创建会员服务(服务发现者)TestUser
public class TestUser {
private static final CountDownLatch countDownLatch = new CountDownLatch(1);
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
ZooKeeper zooKeeper = new ZooKeeper("192.168.100.128:2181", 50000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
Watcher.Event.KeeperState state = watchedEvent.getState();
// 如果当前连接成功,则开始放心
if (state == Event.KeeperState.SyncConnected) {
System.out.println("zk连接成功~~");
countDownLatch.countDown();
}
}
});
countDownLatch.await();
String path = "/jyb-service";
// 获取该节点下子集
List<String> children = zooKeeper.getChildren(path, null, new Stat());
for (int i = 0; i < children.size(); i++) {
String pathChildren = path + "/" + children.get(i);
byte[] data = zooKeeper.getData(pathChildren, null, new Stat());
System.out.println("服务接口地址:" + new String(data));
}
}
}
5.启动springboot项目
将yml文件的port端口号换成8085 8086个启动一次
图片.png
6.查看服务是否注册成功
打开zooInspector客户端工具看是否有8085 8086节点信息
图片.png
7.运行会员服务TestUser
显示如下结果说明会员服务成功获取到订单服务地址信息
图片.png
网友评论