例子
private static boolean wasAcquired = false;// 是否获取了锁
public void tetsZookeeper(){
String serverId = UUID.randomUUID().toString().toLowerCase();
AccountLock lock = new AccountLock("/ACCOUNT/" + serverId,zookeeperConnector);
log.info(“开始获取锁”);
wasAcquired = lock.acquire(3);// 锁
log.info(“获取锁:”+(wasAcquired?“SUCCESS”:“ERROR”));
try{
System.out.println(“11111111”);
Thread.sleep(2000);
return;
}catch (Exception e){
log.error(e.getMessage(),e);
}finally {
log.info(“开始释放锁…”);
lock.release();// 释放锁
}
}
AccountLock类
package com.baibei.pay.utils;
import com.baibei.pay.configurer.ZooKeeperConnector;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import java.util.concurrent.TimeUnit;
@Slf4j
public class AccountLock {
InterProcessMutex lock;
boolean wasAcquired = false;// 是否获取到了锁
public AccountLock(String path, ZooKeeperConnector zookeeperConnector) {
lock = new InterProcessMutex(zookeeperConnector.getClient(), path);
}
/**
* 尝试加锁并等待
*
* @param timeOut
* 超时时间(秒), -1 不限时
* @return true为获取锁成功,false为获取锁失败
*
* @throws Exception
*/
public boolean acquire(int timeOut) {
try {
wasAcquired = lock.acquire(timeOut, TimeUnit.SECONDS);
} catch (Exception e) {
log.error(“get Lock time out ERROR:” + e.getMessage());
wasAcquired = false;
}
return wasAcquired;
}
/**
* 释放锁
*
* @throws Exception
*/
public void release() {
if (wasAcquired) {
try {
lock.release();
} catch (Exception e) {
log.error(“remove Lock ERROR:” + e.getMessage());
}
}
}
}