当前位置:   article > 正文

ZK分布式锁框架curator简单案例_zk 3.5.5 curator

zk 3.5.5 curator

1.引入依赖

  1. <!--zookeeper-->
  2. <dependency>
  3. <groupId>org.apache.zookeeper</groupId>
  4. <artifactId>zookeeper</artifactId>
  5. <version>3.5.7</version>
  6. </dependency>
  7. <!--curator-->
  8. <dependency>
  9. <groupId>org.apache.curator</groupId>
  10. <artifactId>curator-framework</artifactId>
  11. <version>4.3.0</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.apache.curator</groupId>
  15. <artifactId>curator-recipes</artifactId>
  16. <version>4.3.0</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.apache.curator</groupId>
  20. <artifactId>curator-client</artifactId>
  21. <version>4.3.0</version>
  22. </dependency>

2.获取连接实例方法

  1. public static CuratorFramework getCuratorFramework(){
  2. //创建连接实例
  3. CuratorFramework client = CuratorFrameworkFactory.builder().connectString("ZK地址:2182")
  4. .connectionTimeoutMs(50000)
  5. .sessionTimeoutMs(50000)
  6. .retryPolicy(new ExponentialBackoffRetry(50000,3)).build();
  7. client.start();
  8. System.out.println("zookeeper 客户端启动成功了");
  9. return client;
  10. }

3.使用

  1. public static void main(String[] args) {
  2. // 创建分布式锁1
  3. InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/locks");
  4. // 创建分布式锁2
  5. InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/locks");
  6. new Thread(new Runnable() {
  7. @Override
  8. public void run() {
  9. try {
  10. //获取锁
  11. lock1.acquire();
  12. System.out.println("线程1 获取到锁");
  13. Thread.sleep(5000);
  14. //释放锁
  15. lock1.release();
  16. System.out.println("线程1 释放锁");
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }).start();
  22. new Thread(new Runnable() {
  23. @Override
  24. public void run() {
  25. try {
  26. //获取锁
  27. lock2.acquire();
  28. System.out.println("线程2 获取到锁");
  29. Thread.sleep(5000);
  30. //释放锁
  31. lock2.release();
  32. System.out.println("线程2 释放锁");
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }).start();
  38. }

4.测试

  1. 线程2 获取到锁
  2. 线程2 释放锁
  3. 线程1 获取到锁
  4. 线程1 释放锁
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号