1.引入依赖
<!--zookeeper-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.7</version>
</dependency>
<!--curator-->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>4.3.0</version>
</dependency>
2.获取连接实例方法
public static CuratorFramework getCuratorFramework(){
//创建连接实例
CuratorFramework client = CuratorFrameworkFactory.builder().connectString("ZK地址:2182")
.connectionTimeoutMs(50000)
.sessionTimeoutMs(50000)
.retryPolicy(new ExponentialBackoffRetry(50000,3)).build();
client.start();
System.out.println("zookeeper 客户端启动成功了");
return client;
}
3.使用
public static void main(String[] args) {
// 创建分布式锁1
InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/locks");
// 创建分布式锁2
InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/locks");
new Thread(new Runnable() {
@Override
public void run() {
try {
//获取锁
lock1.acquire();
System.out.println("线程1 获取到锁");
Thread.sleep(5000);
//释放锁
lock1.release();
System.out.println("线程1 释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
//获取锁
lock2.acquire();
System.out.println("线程2 获取到锁");
Thread.sleep(5000);
//释放锁
lock2.release();
System.out.println("线程2 释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
4.测试
线程2 获取到锁
线程2 释放锁
线程1 获取到锁
线程1 释放锁
|