1.服务器动态上下线(任意一台客户端都能实时感知到主节点服务器的上下线)
思路:
服务器启动时在Zookeeper上/service下创建临时子节点,下线时会自动删除znode
客户端获取/service下所有子节点(即所有服务)并注册监听,当子节点有变化时会通知客户端并调用process(),同时在process()中再次启动监听
(1)在集群上创建/servers 节点
[zk: localhost:2181(CONNECTED) 10] create /servers "servers"
(2)服务注册
public class ServiceRegistry {
private static ZooKeeper zk = null;
public static void main(String[] args) throws Exception {
getConnect();
createNode();
Thread.sleep(Integer.MAX_VALUE);
}
public static void getConnect() {
try {
zk = new ZooKeeper("192.168.196.129:2181", 30000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createNode() {
try {
String nodeCreated = zk.create("/servers/server", "节点数据".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
} catch (Exception e) {
e.printStackTrace();
}
}
}
(3)客户端
public class zkClient {
private static ZooKeeper zk = null;
public static void main(String[] args) throws Exception {
getConnect();
getChildren();
Thread.sleep(Integer.MAX_VALUE);
}
public static void getConnect() {
try {
zk = new ZooKeeper("192.168.196.129:2181", 30000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("监听回调:" + watchedEvent);
try {
List<String> children = zk.getChildren("/servers", true);
children.forEach(e -> System.out.println(e));
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public static void getChildren() {
try {
List<String> children = zk.getChildren("/servers", true);
children.forEach(e -> System.out.println(e));
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.分布式锁
|