本文主要是介绍Zookeeper协调分布式节点demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Zookeeper协调分布式节点demo
多台服务器和客户端通过第三方组件Zookeeper管理
public class DistributedServer {private static final String connectString = "mini1:2181,mini2:2181,mini3:2181";private static final int sessionTimeout = 2000;private static final String parentNode = "/servers";private ZooKeeper zk = null;/*** 创建到zk的客户端连接*/public void getConnect() throws Exception {zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {@Overridepublic void process(WatchedEvent event) {// 收到事件通知后的回调函数(应该是我们自己的事件处理逻辑)System.out.println(event.getType() + "---" + event.getPath());try {zk.getChildren("/", true);} catch (Exception e) {}}});}/*** 向zk集群注册服务器信息*/public void registerServer(String hostname) throws Exception {String create = zk.create(parentNode + "/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);System.out.println(hostname + "is online.." + create);}/*** 业务功能* @throws InterruptedException*/public void handleBussiness(String hostname) throws InterruptedException {System.out.println(hostname + "start working.....");Thread.sleep(Long.MAX_VALUE);}public static void main(String[] args) throws Exception {// 获取zk连接DistributedServer server = new DistributedServer();server.getConnect();// 利用zk连接注册服务器信息server.registerServer(args[0]);// 启动业务功能server.handleBussiness(args[0]);}}
public class DistributedClient {private static final String connectString = "mini1:2181,mini2:2181,mini3:2181";private static final int sessionTimeout = 2000;private static final String parentNode = "/servers";// 注意:加volatile的意义何在?private volatile List<String> serverList;private ZooKeeper zk = null;/*** 创建到zk的客户端连接*/public void getConnect() throws Exception {zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {@Overridepublic void process(WatchedEvent event) {// 收到事件通知后的回调函数(应该是我们自己的事件处理逻辑)try {//重新更新服务器列表,并且注册了监听 getServerList();} catch (Exception e) {}}});}/*** 获取服务器信息列表*/public void getServerList() throws Exception {// 获取服务器子节点信息,并且对父节点进行监听List<String> children = zk.getChildren(parentNode, true);// 先创建一个局部的list来存服务器信息List<String> servers = new ArrayList<String>();for (String child : children) {// child只是子节点的节点名byte[] data = zk.getData(parentNode + "/" + child, false, null);servers.add(new String(data));}// 把servers赋值给成员变量serverList,已提供给各业务线程使用serverList = servers;//打印服务器列表 System.out.println(serverList);}/*** 业务功能*/public void handleBussiness() throws InterruptedException {System.out.println("client start working.....");Thread.sleep(Long.MAX_VALUE);}public static void main(String[] args) throws Exception {// 获取zk连接DistributedClient client = new DistributedClient();client.getConnect();// 获取servers的子节点信息(并监听),从中获取服务器信息列表 client.getServerList();// 业务线程启动 client.handleBussiness();}}
这篇关于Zookeeper协调分布式节点demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!