import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
/**
* 某分布式系统中,主节点可以有多台,可以动态上下线;
* 任意一台客户端都能实时感知到主节点服务器的上下线。
*/
public class AppServer {
private String groupNode = "sgroup";
private String subNode = "sub";
private CountDownLatch latch = new CountDownLatch(1);
/**
* 连接zookeeper
* @param address server的地址
*/
public void connectZookeeper(String address) throws Exception {
ZooKeeper zk = new ZooKeeper("192.168.1.100:2181", 5000, new Watcher() {
public void process(WatchedEvent event) {
// 不做处理
if(event.getState()==KeeperState.SyncConnected){
latch.countDown();
}
}
});
// 在"/sgroup"下创建子节点
// 子节点的类型设置为EPHEMERAL_SEQUENTIAL, 表明这是一个临时节点, 且在子节点的名称后面加上一串数字后缀
// 将server的地址数据关联到新创建的子节点上
latch.await();
String createdPath = zk.create("http://www.likecs.com/" + groupNode + "http://www.likecs.com/" + subNode, address.getBytes("utf-8"),
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println("create: " + createdPath);
}
/**
* server的工作逻辑写在这个方法中
* 此处不做任何处理, 只让server sleep
*/
public void handle() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) {
// 在参数中指定server的地址
if (args.length == 0) {
System.err.println("The first argument must be server address");
System.exit(1);
}
AppServer as = new AppServer();
try {
as.connectZookeeper(args[0]);
as.handle();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ZKClient工程
<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 ">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fanghao</groupId>
<artifactId>ZKClient</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.11</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId> maven-assembly-plugin </artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>zkClient</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.fanghao.AppClient</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
------------------------------------------------------------------
package com.fanghao;
import java.util.ArrayList;
import java.util.List;