zookeeper 分布式锁
zk服务端
版本为 3.4.0- 使用
zk客户端
为 curator
https://curator.apache.org/curator-framework/index.html
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.0</version>
</dependency>
package zookeeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ZkLockUtil {
private InterProcessMutex interProcessMutex;
public ZkLockUtil(String zkServerAddress, String key) {
CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(zkServerAddress)
.sessionTimeoutMs(5000)
.connectionTimeoutMs(5000)
.retryPolicy(new ExponentialBackoffRetry(3000, 3, 30000))
.build();
client.start();
String path = "/lock/Zk" + key;
interProcessMutex = new InterProcessMutex(client, path);
}
public boolean tryLock(long timeout, TimeUnit unit) {
try {
return interProcessMutex.acquire(timeout, unit);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return false;
}
public boolean unlock() {
try {
interProcessMutex.release();
} catch (Throwable e) {
log.error(e.getMessage(), e);
}
return true;
}
public static void main(String[] args) {
Runnable runnable = () -> {
String name = Thread.currentThread().getName();
ZkLockUtil zkLockUtil = new ZkLockUtil("127.0.0.1:2181", "101");
boolean lock = zkLockUtil.tryLock(100, TimeUnit.SECONDS); // tryLock(2, TimeUnit.SECONDS);
if (lock) {
System.out.println(name + ":获取到锁");
try {
Thread.sleep(10000);
System.out.println(name + ":业务完成");
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
zkLockUtil.unlock();
System.out.println(name + ":释放锁\n");
}
} else {
System.out.println(name + ":未获取到锁");
}
};
new Thread(runnable, "线程1").start();
new Thread(runnable, "线程2").start();
new Thread(runnable, "线程3").start();
}
}