zk 分布式锁没有执行Watcher
代码:
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());
没有执行,是什么原因呢?