java连接zookeeper3种方式
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;
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);
}
}
打印:
Java集成zookeeper笔记
一、引入zookeeper-3.4.5.jar(原生zk包)
slf4j.jar即可,其他还有zkClient和Curator,其中Curator封装的zk客户端组件最好用。
二、手写ZookeeperBase.java
少废话,上代码:
简单的创建连接和增删改查操作:
public class ZookeeperBase{
//zk集群地址(端口号为客户端端口号)
private static final String CONNECT_ADDR = "192.168.241.127:2181,192.168.241.128:2181,192.168.241.129:2181";
//session 超时时间,单位毫秒
private static final int SESSION_OUTTIME = 5000;
//用于阻塞程序执行,直到zk成功连接后再发送继续执行信号,因为zk建立连接是异步的,阻塞是防止程序在zk成功连接前被调用。
private static final CountDownLatch contectedSemaphore = new CountDownLatch (1);
public static void main(String[] args)throws Exception{
Zookeeper zk = new Zookeeper(CONNECT_ADDR,SESSION_OUTTIME,new Watcher()){
@override
public void process(WatcherEvent event){ //WatcherEvent为观察者监听事件
//获取事件状态(与客户端连接状态相关)
KeeperState keeperState = event.getState();
//获取事件类型(与zknode相关)
EventType eventType = event.getType();
//成功建立连接(固定写法)
if(KeeperState.SyncConnected == keeperState){
if(EventType.None == eventType){
//发送信号让程序继续执行
contectedSemaphore.countDown();
}
}
}
//阻塞程序执行
contectedSemaphore.await();
//创建节点
//同步创建
String newNode = zk.create("/testRoot","data".getBytes(),ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
};
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。