当前位置: 首页 > news >正文

分布式锁2-Zookeeper分布式锁实战

Zookeeper分布式锁实战

使用curator操作Zookeeper进行实战;
curator是什么:Apache Curator包含一套高级API框架和工具类,它 是Apache ZooKeeper 的Java 客户端库。

准备

  1. pom文件引入curtor依赖和zookeeper依赖
<!--curator-->
<dependency><groupId>org.apache.curator</groupId><artifactId>curator-recipes</artifactId><version>5.6.0</version>
</dependency><dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId><version>5.6.0</version></dependency>
<!--zookeeper-->
<dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>3.9.2</version>
</dependency>
  1. yml配置
#zookeeper
curator:connectString: localhost:2181retryCount: 5elapsedTimeMs: 5000sessionTimeOutMs: 60000connectionTimeOutMs: 5000
  1. 配置类
/*** @Author * @Date 2024/5/19 19:45*/
@Data
@Component
@ConfigurationProperties(prefix = "curator")
public class WrapperZK {/** 重试次数*/private int retryCount;/** 重试间隔时间*/private int elapsedTimeMs;/** 连接地址*/private String connectString;/** session超时时间*/private int sessionTimeOutMs;/** 连接超时时间*/private int connectionTimeOutMs;
}
@Configuration
public class ZookeeperConfig {@Autowiredprivate WrapperZK wrapperZK;@Beanpublic CuratorFramework curatorFramework(){RetryPolicy retryPolicy = new ExponentialBackoffRetry(wrapperZK.getElapsedTimeMs(),wrapperZK.getRetryCount());CuratorFramework client = CuratorFrameworkFactory.newClient(wrapperZK.getConnectString(), wrapperZK.getSessionTimeOutMs(), wrapperZK.getConnectionTimeOutMs(), retryPolicy);client.start();return client;}
}
  1. 使用
  @Autowiredprivate CuratorFramework curatorFramework;static InterProcessLock zkLock;/** 使用zookeeper分布式锁 */@Transactionalpublic void updateByZookeeperLock(Long id,int count){if(zkLock == null){zkLock = new InterProcessMutex(curatorFramework, "/locks");}try {boolean acquire = zkLock.acquire(10000, TimeUnit.MILLISECONDS);/** 加锁*/if(acquire){Product product = mapper.selectById(id);int newCont = product.getProductCount() - count;product.setProductCount(newCont);if(mapper.updateProduct(product) >0 ){System.out.println("扣减成功!");}else {throw new RuntimeException("扣减失败");}}else {System.out.println("拿不到分布式锁!");}}catch (Exception e){e.printStackTrace();}finally {try {/** 释放锁*/zkLock.release();} catch (Exception e) {throw new RuntimeException(e);}}}
@RestController
@RequestMapping("/product")
public class ProductController {@Autowiredprivate ProductService service;@GetMapping("buy/{id}/{count}")public void buy(@PathVariable long id,@PathVariable int count){service.updateByZookeeperLock(id,count);}
}
  1. 测试
    压测前:

在这里插入图片描述
压测:
在这里插入图片描述
压测后:

在这里插入图片描述
成功!

相关文章:

  • Django中使用Celery(通用方案、官方方案)
  • 一顿五元钱的午餐
  • 141.字符串:重复的字符串(力扣)
  • Stable Diffusion教程
  • Midjourney绘画关键词参数汇总(二)
  • currentTarget指向监听者Target:指向触发者
  • TikTok矩阵管理系统:品牌增长的新引擎
  • Php composer 基础教程
  • 基于springboot+vue的学生考勤管理系统
  • FreeRTOS_同步互斥与通信_队列集_学习笔记
  • MySQL实战——主从异步复制搭建(一主一从)
  • 解决ModuleNotFoundError: No module named ‘open_clip‘问题
  • 三维空间坐标系变换(旋转平移)
  • python实现520表白图案
  • LLama3 | 一. 本地 Web Demo 部署
  • Angular 响应式表单之下拉框
  • Gradle 5.0 正式版发布
  • Javascripit类型转换比较那点事儿,双等号(==)
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • NSTimer学习笔记
  • python大佬养成计划----difflib模块
  • SpiderData 2019年2月13日 DApp数据排行榜
  • Stream流与Lambda表达式(三) 静态工厂类Collectors
  • Theano - 导数
  • vue 配置sass、scss全局变量
  • 阿里云容器服务区块链解决方案全新升级 支持Hyperledger Fabric v1.1
  • 百度地图API标注+时间轴组件
  • 表单中readonly的input等标签,禁止光标进入(focus)的几种方式
  • 初识MongoDB分片
  • 搞机器学习要哪些技能
  • 回顾2016
  • 手写一个CommonJS打包工具(一)
  • 吴恩达Deep Learning课程练习题参考答案——R语言版
  • 交换综合实验一
  • # 深度解析 Socket 与 WebSocket:原理、区别与应用
  • #FPGA(基础知识)
  • #Linux(make工具和makefile文件以及makefile语法)
  • (CPU/GPU)粒子继承贴图颜色发射
  • (Ruby)Ubuntu12.04安装Rails环境
  • (webRTC、RecordRTC):navigator.mediaDevices undefined
  • (附源码)spring boot火车票售卖系统 毕业设计 211004
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (精确度,召回率,真阳性,假阳性)ACC、敏感性、特异性等 ROC指标
  • (每日持续更新)jdk api之StringBufferInputStream基础、应用、实战
  • (排序详解之 堆排序)
  • (使用vite搭建vue3项目(vite + vue3 + vue router + pinia + element plus))
  • (一)pytest自动化测试框架之生成测试报告(mac系统)
  • (原創) X61用戶,小心你的上蓋!! (NB) (ThinkPad) (X61)
  • .NET 4.0中使用内存映射文件实现进程通讯
  • .NET构架之我见
  • .NET与 java通用的3DES加密解密方法
  • [ HTML + CSS + Javascript ] 复盘尝试制作 2048 小游戏时遇到的问题
  • [2019/05/17]解决springboot测试List接口时JSON传参异常
  • [52PJ] Java面向对象笔记(转自52 1510988116)