当前位置:   article > 正文

缓存架构SpringBoot集成Curator实现zookeeper分布式锁

curator elapsedtimems 配置参数

缓存架构SpringBoot集成Curator实现zookeeper分布式锁

这篇文章其实是下篇文章缓存架构之实战演练基于zk分布式锁解决分布式缓存并发冲突问题做理论铺垫的,下篇文章我们就会利用该工具解决分布式缓存并发冲突问题,就是下面这个架构,下篇文章我们会重点讨论:

一、分布式锁简介

1、什么是锁

  • 在单机环境下,当存在多个线程可以同时改变某个共享变量时,就需要同步来实现该功能,使其线程安全。
  • 而同步就是通过锁来实现的。锁保证了同一时刻只有一个线程来修改共享变量。

在单机环境下,Java提供了一些并发安全包可以一定程度上保证线程安全,但是在分布式环境(多机环境)下,这些并发包显得就无能为力了!!

2、什么是分布式

分布式的CAP理论:

任何一个分布式系统都无法同时满足一致性(Consistency)、可用性(Availability)和分区容错性(Partition tolerance),最多只能同时满足两项。

目前很多大型网站及应用都是分布式部署的,分布式场景中的数据一致性问题一直是一个比较重要的话题。基于 CAP理论,很多系统在设计之初就要对这三者做出取舍。在互联网领域的绝大多数的场景中,都需要牺牲强一致性来换取系统的高可用性,系统往往只需要保证最终一致性。

3、什么是分布式锁

顾名思义,分布式锁肯定是用在分布式环境下。在分布式环境下,使用分布式锁的目的也是保证同一时刻只有一个线程来修改共享变量,修改共享缓存……。

下篇文章,我们将分享一个实战案例,就是:缓存架构之实战演练基于zk分布式锁解决分布式缓存并发冲突问题

二、原生zookeeper实现分布式锁

  1. import org.apache.zookeeper.CreateMode;
  2. import org.apache.zookeeper.WatchedEvent;
  3. import org.apache.zookeeper.Watcher;
  4. import org.apache.zookeeper.Watcher.Event.KeeperState;
  5. import org.apache.zookeeper.ZooDefs.Ids;
  6. import org.apache.zookeeper.ZooKeeper;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import java.util.concurrent.CountDownLatch;
  10. /**
  11. * zookeeper工具类:
  12. *
  13. * 更多免费资料,更多高清内容,更多java技术,欢迎访问网站
  14. * 极客慧:www.jikeh.cn
  15. * 如果你希望进一步深入交流,请加入我们的大家庭QQ群:375412858
  16. */
  17. public class ZooKeeperSession {
  18. private static final Logger logger = LoggerFactory.getLogger(ZooKeeperSession.class);
  19. private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
  20. private ZooKeeper zookeeper;
  21. public ZooKeeperSession() {
  22. // 连接zookeeper server,是异步创建会话的,那我们怎么知道zk session建立成功了呢?
  23. // 通过一个监听器+CountDownLatch,来确认真正建立了zk server的连接
  24. try {
  25. this.zookeeper = new ZooKeeper(
  26. "localhost:2181",
  27. 50000,
  28. new ZooKeeperWatcher());
  29. //打印即使状态:验证其是不是异步的?
  30. logger.info(String.valueOf(zookeeper.getState()));
  31. try {
  32. // CountDownLatch:简而言之 初始化——非0;非0——等待;0——往下执行
  33. connectedSemaphore.await();
  34. } catch(InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. logger.info("ZooKeeper session established......");
  38. } catch (Exception e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. /**
  43. * 初始化实例:
  44. */
  45. public static void init() {
  46. getInstance();
  47. }
  48. /**
  49. * 建立zk session的watcher:
  50. */
  51. private class ZooKeeperWatcher implements Watcher {
  52. public void process(WatchedEvent event) {
  53. if(KeeperState.SyncConnected == event.getState()) {
  54. connectedSemaphore.countDown();
  55. }
  56. }
  57. }
  58. /**
  59. * 静态内部类实现单例:
  60. */
  61. private static class Singleton {
  62. private static ZooKeeperSession instance;
  63. static {
  64. instance = new ZooKeeperSession();
  65. }
  66. public static ZooKeeperSession getInstance() {
  67. return instance;
  68. }
  69. }
  70. /**
  71. * 获取单例:
  72. *
  73. * @return
  74. */
  75. public static ZooKeeperSession getInstance() {
  76. return Singleton.getInstance();
  77. }
  78. /**
  79. * 重试获取分布式锁:
  80. *
  81. * @param adId
  82. */
  83. public void acquireDistributedLock(Long adId) {
  84. String path = "/ad-lock-" + adId;
  85. try {
  86. zookeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
  87. logger.info("success to acquire lock for adId = " + adId);
  88. } catch (Exception e) {
  89. // 如果那个广告对应的锁node,已经存在了,就是已经被别人加锁了,那么就这里就会报错
  90. // NodeExistsException
  91. int count = 0;
  92. while(true) {
  93. try {
  94. Thread.sleep(1000);
  95. zookeeper.create(path, "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
  96. } catch (Exception e2) {
  97. count++;
  98. logger.info("the " + count + " times try to acquire lock for adId = " + adId);
  99. continue;
  100. }
  101. logger.info("success to acquire lock for adId = " + adId + " after " + count + " times try......");
  102. break;
  103. }
  104. }
  105. }
  106. /**
  107. * 释放掉分布式锁:
  108. *
  109. * @param adId
  110. */
  111. public void releaseDistributedLock(Long adId) {
  112. String path = "/ad-lock-" + adId;
  113. try {
  114. zookeeper.delete(path, -1);
  115. logger.info("release the lock for adId = " + adId);
  116. } catch (Exception e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. public static void main(String[] args) {
  121. Long adId = 1L;
  122. ZooKeeperSession zkSession = ZooKeeperSession.getInstance();
  123. //1、获取锁:
  124. zkSession.acquireDistributedLock(adId);
  125. //2、执行一些修改共享资源的操作
  126. logger.info("I am updating common resource!");
  127. //3、释放锁
  128. zkSession.releaseDistributedLock(adId);
  129. }
  130. }

三、SpringBoot集成Curator实现zookeeper分布式锁

1、Curator简介

Apache Curator是Netflix公司开源的一个Zookeeper客户端,目前已经是Apache的顶级项目,与Zookeeper提供的原生客户端相比,Curator的抽象层次更高,简化了Zookeeper客户端的开发量,通过封装的一套高级API,里面提供了更多丰富的操作,例如session超时重连、主从选举、分布式计数器、分布式锁等等适用于各种复杂场景的zookeeper操作。

2、SpringBoot集成Curator实现zk分布式锁

1)引入pom依赖
  1. <!-- zookeeper -->
  2. <dependency>
  3. <groupId>org.apache.zookeeper</groupId>
  4. <artifactId>zookeeper</artifactId>
  5. <version>3.4.10</version>
  6. <exclusions>
  7. <exclusion>
  8. <groupId>org.slf4j</groupId>
  9. <artifactId>slf4j-log4j12</artifactId>
  10. </exclusion>
  11. <exclusion>
  12. <groupId>org.slf4j</groupId>
  13. <artifactId>slf4j-api</artifactId>
  14. </exclusion>
  15. <exclusion>
  16. <artifactId>log4j</artifactId>
  17. <groupId>log4j</groupId>
  18. </exclusion>
  19. </exclusions>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.apache.curator</groupId>
  23. <artifactId>curator-framework</artifactId>
  24. <version>2.12.0</version>
  25. <exclusions>
  26. <exclusion>
  27. <groupId>org.slf4j</groupId>
  28. <artifactId>slf4j-api</artifactId>
  29. </exclusion>
  30. </exclusions>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.apache.curator</groupId>
  34. <artifactId>curator-recipes</artifactId>
  35. <version>2.12.0</version>
  36. <exclusions>
  37. <exclusion>
  38. <groupId>org.slf4j</groupId>
  39. <artifactId>slf4j-log4j12</artifactId>
  40. </exclusion>
  41. </exclusions>
  42. </dependency>
2)基本配置
  1. #重试次数
  2. curator.retryCount=5
  3. #重试间隔时间
  4. curator.elapsedTimeMs=5000
  5. # zookeeper 地址
  6. curator.connectString=127.0.0.1:2181
  7. # session超时时间
  8. curator.sessionTimeoutMs=60000
  9. # 连接超时时间
  10. curator.connectionTimeoutMs=5000
3)连接配置
  1. package com.jikeh.config;
  2. import org.apache.curator.framework.CuratorFramework;
  3. import org.apache.curator.framework.CuratorFrameworkFactory;
  4. import org.apache.curator.retry.RetryNTimes;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. @Configuration
  9. public class CuratorConfiguration {
  10. @Value("${curator.retryCount}")
  11. private int retryCount;
  12. @Value("${curator.elapsedTimeMs}")
  13. private int elapsedTimeMs;
  14. @Value("${curator.connectString}")
  15. private String connectString;
  16. @Value("${curator.sessionTimeoutMs}")
  17. private int sessionTimeoutMs;
  18. @Value("${curator.connectionTimeoutMs}")
  19. private int connectionTimeoutMs;
  20. @Bean(initMethod = "start")
  21. public CuratorFramework curatorFramework() {
  22. return CuratorFrameworkFactory.newClient(
  23. connectString,
  24. sessionTimeoutMs,
  25. connectionTimeoutMs,
  26. new RetryNTimes(retryCount, elapsedTimeMs));
  27. }
  28. }
4)Curator实现zk分布式锁工具类
  1. package com.jikeh.lock;
  2. import org.apache.curator.framework.CuratorFramework;
  3. import org.apache.curator.framework.recipes.cache.PathChildrenCache;
  4. import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
  5. import org.apache.zookeeper.CreateMode;
  6. import org.apache.zookeeper.ZooDefs;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.InitializingBean;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.stereotype.Service;
  12. import java.util.concurrent.CountDownLatch;
  13. @Service
  14. public class DistributedLockByCurator implements InitializingBean{
  15. private static final Logger logger = LoggerFactory.getLogger(DistributedLockByCurator.class);
  16. private final static String ROOT_PATH_LOCK = "rootlock";
  17. private CountDownLatch countDownLatch = new CountDownLatch(1);
  18. @Autowired
  19. private CuratorFramework curatorFramework;
  20. /**
  21. * 获取分布式锁
  22. */
  23. public void acquireDistributedLock(String path) {
  24. String keyPath = "/" + ROOT_PATH_LOCK + "/" + path;
  25. while (true) {
  26. try {
  27. curatorFramework
  28. .create()
  29. .creatingParentsIfNeeded()
  30. .withMode(CreateMode.EPHEMERAL)
  31. .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
  32. .forPath(keyPath);
  33. logger.info("success to acquire lock for path:{}", keyPath);
  34. break;
  35. } catch (Exception e) {
  36. logger.info("failed to acquire lock for path:{}", keyPath);
  37. logger.info("while try again .......");
  38. try {
  39. if (countDownLatch.getCount() <= 0) {
  40. countDownLatch = new CountDownLatch(1);
  41. }
  42. countDownLatch.await();
  43. } catch (InterruptedException e1) {
  44. e1.printStackTrace();
  45. }
  46. }
  47. }
  48. }
  49. /**
  50. * 释放分布式锁
  51. */
  52. public boolean releaseDistributedLock(String path) {
  53. try {
  54. String keyPath = "/" + ROOT_PATH_LOCK + "/" + path;
  55. if (curatorFramework.checkExists().forPath(keyPath) != null) {
  56. curatorFramework.delete().forPath(keyPath);
  57. }
  58. } catch (Exception e) {
  59. logger.error("failed to release lock");
  60. return false;
  61. }
  62. return true;
  63. }
  64. /**
  65. * 创建 watcher 事件
  66. */
  67. private void addWatcher(String path) throws Exception {
  68. String keyPath;
  69. if (path.equals(ROOT_PATH_LOCK)) {
  70. keyPath = "/" + path;
  71. } else {
  72. keyPath = "/" + ROOT_PATH_LOCK + "/" + path;
  73. }
  74. final PathChildrenCache cache = new PathChildrenCache(curatorFramework, keyPath, false);
  75. cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
  76. cache.getListenable().addListener((client, event) -> {
  77. if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)) {
  78. String oldPath = event.getData().getPath();
  79. logger.info("success to release lock for path:{}", oldPath);
  80. if (oldPath.contains(path)) {
  81. //释放计数器,让当前的请求获取锁
  82. countDownLatch.countDown();
  83. }
  84. }
  85. });
  86. }
  87. //创建父节点,并创建永久节点
  88. @Override
  89. public void afterPropertiesSet() {
  90. curatorFramework = curatorFramework.usingNamespace("lock-namespace");
  91. String path = "/" + ROOT_PATH_LOCK;
  92. try {
  93. if (curatorFramework.checkExists().forPath(path) == null) {
  94. curatorFramework.create()
  95. .creatingParentsIfNeeded()
  96. .withMode(CreateMode.PERSISTENT)
  97. .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
  98. .forPath(path);
  99. }
  100. addWatcher(ROOT_PATH_LOCK);
  101. logger.info("root path 的 watcher 事件创建成功");
  102. } catch (Exception e) {
  103. logger.error("connect zookeeper fail,please check the log >> {}", e.getMessage(), e);
  104. }
  105. }
  106. }
5)测试控制器
  • 首先访问链接(线程1):http://localhost:1111/curator/lock1 首先拿到锁,锁保持20s,操作,放锁

  • 再访问链接(线程2):http://localhost:1111/curator/lock2 等待获取锁,锁保持15s,操作,放锁

  • 结果分析

注释:红色——线程1执行结果;蓝色——线程2执行结果;

代码下载地址https://gitee.com/jikeh/JiKeHCN-RELEASE.git 项目名:spring-boot-curator

更多内容,请关注:

头条号:极客慧

个人网站:极客慧

更多资料分享,请入群讨论:375412858

转载于:https://my.oschina.net/jikeh/blog/2219012

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/911394
推荐阅读
相关标签
  

闽ICP备14008679号