使用curator实现zookeeper锁服务的示例分享
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.netflix.curator.RetryPolicy;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.framework.recipes.locks.InterProcessMutex;
import com.netflix.curator.retry.ExponentialBackoffRetry;
public class TestCuratorLock {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
CountDownLatch latch = new CountDownLatch(5);
String zookeeperConnectionString = "localhost:2181,localhost:2182,localhost:2183";
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(
zookeeperConnectionString, retryPolicy);
client.start();
System.out.println("客户端启动。。。。");
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
exec.submit(new MyLock("client" + i, client, latch));
}
exec.shutdown();
latch.await();
System.out.println("所有任务执行完毕");
client.close();
System.out.println("客户端关闭。。。。");
}
static class MyLock implements Runnable {
private String name;
private CuratorFramework client;
private CountDownLatch latch;
public MyLock(String name, CuratorFramework client, CountDownLatch latch) {
this.name = name;
this.client = client;
this.latch = latch;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void run() {
// TODO Auto-generated method stub
InterProcessMutex lock = new InterProcessMutex(client,
"/test_group");
try {
if (lock.acquire(120, TimeUnit.SECONDS)) {
try {
// do some work inside of the critical section here
System.out.println("----------" + this.name
+ "获得资源----------");
System.out.println("----------" + this.name
+ "正在处理资源----------");
Thread.sleep(10 * 1000);
System.out.println("----------" + this.name
+ "资源使用完毕----------");
latch.countDown();
} finally {
lock.release();
System.out.println("----------" + this.name
+ "释放----------");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
相关文章
SpringBoot使用freemarker导出word文件方法详解
这篇文章主要介绍了SpringBoot使用freemarker导出word文件方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧2022-11-11spring security动态配置url权限的2种实现方法
对于使用spring security来说,存在一种需求,就是动态去配置url的权限,即在运行时去配置url对应的访问角色。下面这篇文章主要给大家介绍了关于spring security动态配置url权限的2种实现方法,需要的朋友可以参考下2018-06-06深入了解Java核心类库--BigDecimal和System类
这篇文章主要为大家详细介绍了javaBigDecimal和System类定义与使用的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能给你带来帮助2021-07-07Spring Security Remember me使用及原理详解
这篇文章主要介绍了Spring Security Remember me使用及原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-09-09
最新评论