java连接zookeeper的3种方式
1、使用zookeeper原始apipublic class Demo {private static String ip = "192.168.0.101:2181";private static intsession_timeout = 40000;private static CountDownLatch latch = new CountDow...
·
1、使用zookeeper原始api
public class Demo {
private static String ip = "192.168.0.101:2181";
private static int session_timeout = 40000;
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) throws Exception {
ZooKeeper zooKeeper = new ZooKeeper(ip, session_timeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
if(watchedEvent.getState() == Event.KeeperState.SyncConnected) {
//确认已经连接完毕后再进行操作
latch.countDown();
System.out.println("已经获得了连接");
}
}
});
//连接完成之前先等待
latch.await();
ZooKeeper.States states = zooKeeper.getState();
System.out.println(states);
}
}
打印:
如果打印出来的状态为 CONNECTED 则表示连接成功
2、使用ZkClient客户端连接,这种连接比较简单
public class ZkClientTest {
private static String ip = "192.168.0.101:2181";
private static int session_timeout = 40000;
public static void main(String[] args) {
ZkClient zkClient = new ZkClient(ip,session_timeout);
System.out.println(zkClient.getChildren("/"));
}
}
打印:
3、 使用curator连接:
public class CuratorDemo {
//ZooKeeper服务地址
private static final String SERVER = "192.168.0.101:2181";
//会话超时时间
private static final int SESSION_TIMEOUT = 30000;
//连接超时时间
private static final int CONNECTION_TIMEOUT = 5000;
/**
* baseSleepTimeMs:初始的重试等待时间
* maxRetries:最多重试次数
*
*
* ExponentialBackoffRetry:重试一定次数,每次重试时间依次递增
* RetryNTimes:重试N次
* RetryOneTime:重试一次
* RetryUntilElapsed:重试一定时间
*/
private static final RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
public static void main(String[] args) throws Exception {
//创建 CuratorFrameworkImpl实例
CuratorFramework client = CuratorFrameworkFactory.newClient(SERVER, SESSION_TIMEOUT, CONNECTION_TIMEOUT, retryPolicy);
//启动
client.start();
System.out.println("连接成功!");
Object o = client.getChildren().forPath("/");
System.out.println(o);
}
}
打印:
以上
更多推荐
所有评论(0)