标签:mkdir val 应用 exist ring rand apache /tmp ade
1 <dependencies> 2 <dependency> 3 <groupId>org.apache.zookeeper</groupId> 4 <artifactId>zookeeper</artifactId> 5 <version>3.4.10</version> 6 </dependency> 7 </dependencies>
1 public class ZkClient implements Watcher { 2 3 static CountDownLatch connected = new CountDownLatch(1); 4 static final String CONN_STR = "192.168.217.170:2181,192.168.217.171:2181,192.168.217.172:2181"; 5 6 public void test() throws Exception { 7 ZooKeeper zoo = null; 8 9 zoo = new ZooKeeper(CONN_STR, 5000, this); 10 System.out.println(zoo.getState()); 11 12 connected.await(); 13 14 if (zoo.exists("/skyer", false) != null) { 15 zoo.delete("/skyer", -1); 16 } 17 18 zoo.create("/skyer", "192.168.56.1:2000".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 19 System.out.println("ok"); 20 21 byte[] data = zoo.getData("/skyer", false, null); 22 System.out.println(new String(data)); 23 24 zoo.create("/e", "e".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 25 26 Thread.sleep(10000); 27 zoo.close(); 28 } 29 30 public static void main(String[] args) throws Exception { 31 new ZkClient().test(); 32 } 33 34 public void process(WatchedEvent event) { 35 System.out.println("event:" + event); 36 if (event.getState() == KeeperState.SyncConnected) { 37 connected.countDown(); 38 System.out.println("connected!"); 39 } 40 } 41 42 }
1 public class TankMaster { 2 3 static String status = "ACTIVE"; 4 5 public static void main(String[] args) throws Exception { 6 String CONN_STR = "192.168.217.170:2181,192.168.217.171:2181,192.168.217.172:2181"; 7 ZooKeeper zk = new ZooKeeper(CONN_STR, 5000, null); 8 9 String IP = "202.106.29.138"; 10 String port = new Random().nextInt(500) + ""; 11 System.out.println(port); 12 13 if (zk.exists("/tankMaster", new MasterWatcher()) != null) { 14 status = "STANDBY"; 15 } else { 16 zk.create("/tankMaster", (IP + ":" + port).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 17 status = "ACTIVE"; 18 // 启动server 19 System.out.println("启动就是active"); 20 } 21 Thread.sleep(Integer.MAX_VALUE); 22 } 23 24 static class MasterWatcher implements Watcher { 25 public void process(WatchedEvent event) { 26 if (event.getType() == EventType.NodeDeleted) { 27 status = "ACTIVE"; 28 System.out.println("切换为active"); 29 } 30 } 31 } 32 33 }
标签:mkdir val 应用 exist ring rand apache /tmp ade
原文地址:http://www.cnblogs.com/skyer5217/p/7680513.html