原生API-main测试
代码
public static void main(String[] args) throws IOException {
//集群地址,可以设置连接上的根目录
String connectString = "localhost:2181";
//会话超时:检测到心跳后,再次在这个时间段内监听💓,没有c-s之间的连接失效??
int sessionTimeout = 60*1000;
//基于watch判断客户-服务端之间是否建立连接
CountDownLatch countDownLatch = new CountDownLatch(1);
//客户端实列,构造器选择
//需要注意的是,会话建立是异步过程,构造方法会在调用后立刻返回,此时并没有建立好一个可用的会话
//会话真正创建完毕后,s向c发送事件通知,客户获得后才算建立了真正会话,通过watcher监听
//构造方法内部实现了TCP连接,维护客户端会话生命周期
ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
// 收到SyncConnected事件,表示会话建立成功,解除CountDownLatch阻塞
if(Event.KeeperState.SyncConnected==watchedEvent.getState()){
countDownLatch.countDown();
}
}
});
System.out.printf("客户端连接进度:"+zooKeeper.getState());
try {
countDownLatch.await();
System.out.printf("客户端连接进度:"+zooKeeper.getState());
}catch (Exception e){
}
}
检查
原生API-集成到springboot
config代码
- 注入为bean
public class ZkConfig {
@Value("${zk.connectString}")
private String connectString;
@Value("${zk.sessionTimeout}")
private int sessionTimeout;
private CountDownLatch countDownLatch = new CountDownLatch(1);
@Bean(name = "zkClient")
public ZooKeeper initZk(){
ZooKeeper zkClient = null;
try{
zkClient = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
@Override
public void process(WatchedEvent watchedEvent) {
if(watchedEvent.getState().equals(Event.KeeperState.SyncConnected)){
log.info("与zk服务器连接状态:"+watchedEvent.getState());
countDownLatch.countDown();
}
}
});
log.info("与zk服务器连接状态:"+zkClient.getState());
countDownLatch.await();
log.info("与zk服务器连接状态:"+zkClient.getState());
}catch (Exception e){
log.error(e.getMessage());
}
return zkClient;
}
}
检查