通过Java来操作Zookeeper
环境:三台服务器
1. 192.168.248.128:2181 --centos6.9 2. 192.168.248.129:2181 --centos6.9 3. 192.168.248.130:2181 --centos7.4
项目的创建,工具:idea,工程:maven工程
导入依赖:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- 坐标 --> <groupId>com.ghq.zoo</groupId> <artifactId>zoodemo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.hadoop/zookeeper --> <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>zookeeper</artifactId> <version>3.3.1</version> </dependency> <!-- junit的依赖 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> </dependency> </dependencies> <packaging>jar</packaging> <name>zoodemo</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 指定编译器的版本 --> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> </project>
测试对数据的CRUD操作
package com.ghq.zoo; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; /** * Hello world! * */ public class SimpleZkClient { //服务器的ip地址和端口 private static final String connectString = "192.168.248.130:2181,192.168.248.128:2181,192.168.248.129:2181"; //连接等待时间 private static final int sessionTimeout = 30000; // private static final Watcher watcher = new Watcher() { // @Override // public void process(WatchedEvent event) { // System.out.println(event.getType()); // System.out.println(event.getPath()); // // } // }; static ZooKeeper zkClient = null; @Before public void init() throws Exception { zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() { //监听事件,每次数据修改都会重新执行查询操作 @Override public void process(WatchedEvent event) { //收到事件通知后的回调函数 System.out.println(event.getType()+"----------path:"+event.getPath()); try { zkClient.getChildren("/",true); } catch (Exception e) { e.printStackTrace(); } } }); } //创建数据节点 @Test public void testCreate() { try { /** * 数据的创建 * @param path: 创建的数据的路径 * @param data: 创建的数据 * @param acl 创建数据的权限 * @param mode 创建数据的类型 */ String s = zkClient.create("/ecqwe", "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (Exception e) { e.printStackTrace(); } } //判断节点是否存在 @Test public void testExist() throws KeeperException, InterruptedException { Stat stat = zkClient.exists("/eclipse", false); System.out.println(stat==null?"not exist":"exist"); } //获取子节点 @Test public void getChildren() throws Exception { List<String> children = zkClient.getChildren("/", true); for (String s: children) { System.out.println(s); } Thread.sleep(Long.MAX_VALUE); } //获取节点数据 @Test public void getData() throws Exception { byte[] data = zkClient.getData("/eclipse", false, null); System.out.println(new String(data,"utf-8")); } //删除数据 @Test public void delData() throws KeeperException, InterruptedException { zkClient.delete("/ec",-1); } //修改数据 @Test public void updateData() throws KeeperException, InterruptedException { zkClient.setData("/aaaa","asdfg".getBytes(),-1); } }
服务器上下线的通知
服务器端的代码
package com.ghq.zklist; import org.apache.zookeeper.*; import java.io.IOException; public class DistributedServer { private static final String connectString = "192.168.248.130:2181,192.168.248.128:2181,192.168.248.129:2181"; private static final int sessionTimeout = 30000; private ZooKeeper zkClient = null; //获取zk连接 public void getConnect() throws IOException { zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { //收到事件通知后的回调函数 // System.out.println(event.getType()+"----------path:"+event.getPath()); try { zkClient.getChildren("/",true); } catch (Exception e) { e.printStackTrace(); } } }); } private static final String parentNode = "/servers"; /** * 注册一个服务器 * * 权限控制:ZooDefs.Ids.OPEN_ACL_UNSAFE * 节点的类型:CreateMode.EPHEMERAL_SEQUENTIAL (临时有序的,这样服务器宕机之后该 * 节点删除,会通知给各个客户端和服务器) */ public void registerServer(String hostname) throws Exception { String create = zkClient.create(parentNode + "/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); System.out.println(hostname+"is online..."+create); } //业务功能 public void handleBusiness(String hostname){ System.out.println(hostname+"start working"); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } } //主方法 public static void main(String[] args) throws Exception { DistributedServer server = new DistributedServer(); //获取zk连接 server.getConnect(); String hostname = "192.168.248.128"; //通过zk连接注册服务信息 server.registerServer(hostname); //处理业务逻辑 server.handleBusiness(hostname); } }
客户端的代码
package com.ghq.zklist; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class DistributedClient { private static final String connectString = "192.168.248.130:2181,192.168.248.128:2181,192.168.248.129:2181"; private static final int sessionTimeout = 30000; private ZooKeeper zkClient = null; private static final String parentNode = "/servers"; //获取zk连接 public void getConnect() throws IOException { zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { //收到事件通知后的回调函数 // System.out.println(event.getType()+"----------path:"+event.getPath()); try { //这里监听响应 //重新更新服务器列表, getServerList(); } catch (Exception e) { e.printStackTrace(); } } }); } /** * 加 volatile的意义何在? * volatile的工作机制:再说明 */ private volatile List<String> serverList = null; //获取服务器信息列表 public void getServerList() throws Exception { //获取到子节点 List<String> children = zkClient.getChildren(parentNode, true); //拿到子节点的数据 List<String> serversData = new ArrayList<>(); for (String child:children){ //child只是节点的名字 byte[] data = zkClient.getData(parentNode + "/" + child, false, null); serversData.add(new String(data,"UTF-8")); } //把serversData赋值给成员变量serverList serverList = serversData;//瞬间赋值完成,不要一个一个添加 //打印服务器列表 System.out.println(serverList); } //业务功能 public void handleBusiness(){ System.out.println("client start working"); try { Thread.sleep(Long.MAX_VALUE); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { //获取zk连接,需要注册监听器 DistributedClient client = new DistributedClient(); client.getConnect(); //获取servers的子节点信息(并监听),从中获取服务器信息列表 client.getServerList(); //调用业务逻辑方法 client.handleBusiness(); } }
结束!!!