zk 分布式锁没有执行Watcher

wangsufu77 2019-06-17 10:31:31
代码:

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;


public class ZooKeeperSession {

private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

private ZooKeeper zookeeper;

public ZooKeeperSession() {

try {
this.zookeeper = new ZooKeeper(
"192.168.31.106:9092,192.168.31.51:9092,192.168.31.236:9092",
50000,
new ZooKeeperWatcher());

System.out.println(zookeeper.getState());

try {
connectedSemaphore.await();
} catch(InterruptedException e) {
e.printStackTrace();
}

} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 获得分布式锁
* @param productId
*/
public void acquireDistributedLock(Long productId) {
String path = "/product-lock-" + productId;

try {
zookeeper.create(path, "".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println("success to acquire lock for product[id=" + productId + "]");
} catch (Exception e) {

}

/**
* 释放锁
* @param productId
*/
public void releaseDistributedLock(Long productId) {
String path = "/product-lock-" + productId;
try {
zookeeper.delete(path, -1);
} catch (Exception e) {
e.printStackTrace();
}
}


private class ZooKeeperWatcher implements Watcher {

public void process(WatchedEvent event) {
System.out.println("Receive watched event: " + event.getState());
if(KeeperState.SyncConnected == event.getState()) {
connectedSemaphore.countDown();
}
}

}


private static class Singleton {

private static ZooKeeperSession instance;

static {
instance = new ZooKeeperSession();
}

public static ZooKeeperSession getInstance() {
return instance;
}

}


public static ZooKeeperSession getInstance() {
return Singleton.getInstance();
}


public static void init() {
getInstance();
}



}

测试代码

public class ZK2 {
public static void main(String[] args) {
ZooKeeperSession.init();
ZooKeeperSession zooKeeperSession= ZooKeeperSession.getInstance();
System.out.println("11111111111");
zooKeeperSession.acquireDistributedLock(345L);
System.out.println("2222222222");
zooKeeperSession.releaseDistributedLock(345L);
System.out.println("333333333");
}
}
问题:
这句代码
public void process(WatchedEvent event) {
System.out.println("Receive watched event: " + event.getState());
没有执行,是什么原因呢?

...全文
56 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧