ZooKeeper之API应用
1. 环境搭建
创建一个Maven工程
添加pom文件、
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.8.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.10</version> </dependency> </dependencies>
拷贝log4j.properties文件到项目根目录
需要在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”
log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.File=target/spring.log log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
2. 创建ZooKeeper客户端
/**
* @Date 2020/7/16 16:05
* @Version 10.21
* @Author DuanChaojie
*/
public class ZooKeeperClient {
private String connectString = "hadoop:2181,hadoop101:2181,hadoop:2181";
private int sessionTimeout = 2000;
private ZooKeeper zkClient;
@Before
public void init() throws IOException {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
try {
List<String> children = zkClient.getChildren("/", true);
System.out.println("----start-------");
for (String child : children) {
System.out.println("child = " + child);
}
System.out.println("----end---------");
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("zkClient = " + zkClient);
}
@Test
public void create() throws KeeperException, InterruptedException {
// final String path, byte data[], List<ACL> acl, CreateMode createMode
// 参数1:要创建的节点的路径; 参数2:节点数据 ; 参数3:节点权限 ;参数4:节点的类型
String node = zkClient.create("/atguigu", "atguigu".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@Test
public void getChildren() throws KeeperException, InterruptedException {
List<String> children = zkClient.getChildren("/", true);
for (String child : children) {
System.out.println("child = " + child);
}
Thread.sleep(Long.MAX_VALUE);
}
// 判断znode是否存在
@Test
public void exist() throws Exception {
Stat stat = zkClient.exists("/atguigu", false);
System.out.println(stat == null ? "not exist" : "exist");
}
}
3. 监听服务器节点动态上下线案例
需求:某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
代码实现
#先在集群上创建/servers节点
create /servers "servers"
服务器端向Zookeeper注册代码
将服务器注册到ZooKeeper集群中
/**
* @Date 2020/7/16 18:02
* @Version 10.21
* @Author DuanChaojie
*/
public class DistributeServer {
private String connectString = "hadoop:2181,hadoop101:2181,hadoop102:2181";
private int sessionTimout = 2000;
private ZooKeeper zkClient;
private String parentNode = "/servers";
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
args = new String[]{"hadoop:2181"};
DistributeServer server = new DistributeServer();
// 1.获取zk连接
server.getConnect();
// 2.利用zk连接注册服务器信息
server.registServer(args[0]);
// 3.启动业务功能
server.business(args[0]);
}
private void business(String hostname) throws InterruptedException {
System.out.println(hostname+" is working ...");
Thread.sleep(Long.MAX_VALUE);
}
private void registServer(String hostname) throws KeeperException, InterruptedException {
String create = zkClient.create(parentNode + "/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(hostname + "is online" + create);
}
private void getConnect() throws IOException {
zkClient = new ZooKeeper(connectString, sessionTimout, new Watcher() {
public void process(WatchedEvent event) {
}
});
}
}
客户端代码
监听ZooKeeper的
/**
* @Date 2020/7/16 18:33
* @Version 10.21
* @Author DuanChaojie
*/
public class DistributeClient {
private String connectString = "hadoop:2181,hadoop101:2181,hadoop102:2181";
private int sessionTimeout = 2000;
private ZooKeeper zk = null;
private String parentNode = "/servers";
public static void main(String[] args) throws Exception {
args = new String[]{"hadoop:2181"};
// 1获取zk连接
DistributeClient client = new DistributeClient();
client.getConnect();
// 2获取servers的子节点信息,从中获取服务器信息列表
client.getServerList();
// 3业务进程启动
client.business();
}
private void business() throws InterruptedException {
System.out.println("client is working ...");
Thread.sleep(Long.MAX_VALUE);
}
private void getServerList() throws KeeperException, InterruptedException {
// 1获取服务器子节点信息,并且对父节点进行监听
List<String> children = zk.getChildren(parentNode, true);
// 2存储服务器信息列表
ArrayList<String> servers = new ArrayList<>();
// 3遍历所有节点,获取节点中的主机名称信息
for (String child : children) {
byte[] data = zk.getData(parentNode + "/" + child, false, null);
servers.add(new String(data));
}
// 4打印服务器列表信息
System.out.println(servers);
}
private void getConnect() throws IOException {
// 创建到zk的客户端连接
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
// 再次启动监听
try {
getServerList();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}