
top.zopx.square.distributed.lock.ZkLock Maven / Gradle / Ivy
The newest version!
package top.zopx.square.distributed.lock;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.zopx.square.distributed.core.exception.BusException;
import java.util.concurrent.TimeUnit;
/**
* @author 俗世游子
* @date 2021/11/19
* @email [email protected]
*/
public class ZkLock extends BaseLock {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkLock.class);
private final String lockPath;
private final CuratorFramework client;
private InterProcessLock lock;
public ZkLock(CuratorFramework client, String lockPath) {
this.client = client;
this.lockPath = lockPath;
}
@Override
public void lock() {
try {
this.lock.acquire();
} catch (Exception e) {
LOGGER.error("Lock异常,异常信息:{}", e.getMessage());
throw new BusException(e);
}
}
@Override
public boolean tryLock() {
boolean isLocked;
try {
isLocked = this.lock.acquire(0, TimeUnit.SECONDS);
} catch (Exception e) {
LOGGER.error("tryLock异常,异常信息:{}", e.getMessage());
throw new BusException(e);
}
return isLocked;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
boolean isLocked;
try {
isLocked = this.lock.acquire(time, unit);
} catch (Exception e) {
LOGGER.error("tryLock异常,异常信息:{}", e.getMessage());
throw new BusException(e);
}
return isLocked;
}
@Override
public void unlock() {
try {
this.lock.release();
} catch (Exception e) {
LOGGER.error("unlock异常,异常信息:{}", e.getMessage());
throw new BusException(e);
}
}
@Override
public void init() {
this.lock = defaultLock(lockPath);
}
/**
* 公平可重入锁
*
* @param lockPath 路径
* @return InterProcessMutex
*/
InterProcessLock defaultLock(String lockPath) {
return new InterProcessMutex(client, lockPath);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy