创建zookeeper客户端
private CountDownLatch countDownLatch = new CountDownLatch ( 1 ) ;
ZooKeeper zooKeeper;
public ZooLock ( ) {
try {
zooKeeper = new ZooKeeper ( "127.0.0.1:2181" , 3000 , new Watcher ( ) {
@Override
public void process ( WatchedEvent event) {
if ( event. getType ( ) == EventType. None) {
if ( event. getState ( ) == KeeperState. SyncConnected) {
System. out. println ( "connect success" ) ;
countDownLatch. countDown ( ) ;
}
}
}
} ) ;
countDownLatch. await ( ) ;
} catch ( Exception e) {
System. out. println ( "e= " + e. getMessage ( ) ) ;
}
}
获取锁
private static String LOCK_ROOT_PATH = "/locks" ;
private static String LOCK_NODE_NAME = "lock_" ;
private String lockPath;
public void tryLock ( ) throws KeeperException, InterruptedException {
createNode ( ) ;
lock ( ) ;
}
Watcher watcher = new Watcher ( ) {
@Override
public void process ( WatchedEvent event) {
if ( event. getType ( ) == EventType. NodeDeleted) {
synchronized ( this ) {
notify ( ) ;
}
}
}
} ;
private void createNode ( ) throws KeeperException, InterruptedException {
Stat stat = zooKeeper. exists ( LOCK_ROOT_PATH, false ) ;
if ( stat == null) {
zooKeeper. create ( LOCK_ROOT_PATH, new byte [ 0 ] , Ids. OPEN_ACL_UNSAFE, CreateMode. PERSISTENT) ;
}
lockPath = zooKeeper. create ( LOCK_ROOT_PATH+ "/" + LOCK_NODE_NAME, new byte [ 0 ] , Ids. OPEN_ACL_UNSAFE, CreateMode. EPHEMERAL_SEQUENTIAL) ;
System. out. println ( "节点创建成功" + lockPath) ;
}
private void lock ( ) throws KeeperException, InterruptedException {
List< String> list = zooKeeper. getChildren ( LOCK_ROOT_PATH, false ) ;
Collections. sort ( list) ;
int index = list. indexOf ( lockPath. substring ( LOCK_ROOT_PATH. length ( ) + 1 ) ) ;
if ( index == 0 ) {
return ;
} else {
String lastPath = list. get ( index - 1 ) ;
Stat stat = zooKeeper. exists ( LOCK_ROOT_PATH+ "/" + lastPath, watcher) ;
if ( stat == null) {
lock ( ) ;
} else {
synchronized ( watcher) {
watcher. wait ( ) ;
}
lock ( ) ;
}
}
}
释放锁
public void releaseLock ( ) throws KeeperException, InterruptedException {
zooKeeper. delete ( lockPath, - 1 ) ;
zooKeeper. close ( ) ;
System. out. println ( "锁已经释放." ) ;
}
测试
public void sellWithLock ( ) throws KeeperException, InterruptedException {
ZooLock zooLock = new ZooLock ( ) ;
zooLock. tryLock ( ) ;
sell ( ) ;
zooLock. releaseLock ( ) ;
}
private void sell ( ) {
System. out. println ( "start sell" ) ;
try {
TimeUnit. SECONDS. sleep ( 5 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System. out. println ( "end sell" ) ;
}
public static void main ( String[ ] args) throws KeeperException, InterruptedException {
TickSeller tickSeller = new TickSeller ( ) ;
for ( int i = 0 ; i < 10 ; i++ ) {
tickSeller. sellWithLock ( ) ;
}
}