Redission和Zookeeper分别实现分布式锁

article/2025/10/31 3:14:38

Redission和Zookeeper分别实现分布式锁(windows)

1、Redission实现分布式事务

1.1 前提准备

  • 下载好nginx(windows版本)
  • 下载好Jmeter(模仿高并发)
  • 下载好redis(windows版)

1.2 代码

  • pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.2</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>cn.lanqiao</groupId><artifactId>arcdemo</artifactId><version>0.0.1-SNAPSHOT</version><name>arcdemo</name><description>arcdemo</description><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- redisson --><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.17.5</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
  • 配置文件
  • 因为实现分布式事务,所以一会再启动一个9000端口的该项目
# 应用名称
spring.application.name=arcdemo
# 应用服务 WEB 访问端口
server.port=8000# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000
  • 在主启动类注入Redisson
package com.example;import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;@SpringBootApplication
@EnableRedisHttpSession
public class ArcdemoApplication {public static void main(String[] args) {SpringApplication.run(ArcdemoApplication.class, args);}@Beanpublic Redisson redission() {Config config = new Config();config.useSingleServer().setAddress("redis://localhost:6379").setDatabase(0);return (Redisson) Redisson.create(config);}}
  • controller类
package com.example.controller;import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;/*** @Author Devere19* @Date 2022/8/17 10:41* @Version 1.0*/
@RestController
public class BiSheController {// private static final String ZK_ADDRESS = "127.0.0.1:2181";//// private static final String ZK_LOCK_PATH = "/zkLock";//// static CuratorFramework client = null;//// static {//     //连接zk//     client = CuratorFrameworkFactory.newClient(ZK_ADDRESS,//             new RetryNTimes(10, 5000));//     client.start();// }// 分布式锁@Autowiredprivate Redisson redisson;@Resourceprivate StringRedisTemplate stringRedisTemplate;@GetMapping("/login")public String login(String username, HttpSession session, HttpServletRequest request) {session.setAttribute("username", username);return username + ",端口" + request.getLocalPort();}@GetMapping("/getUser")public String getUser(HttpSession session, HttpServletRequest request) {String username = (String) session.getAttribute("username");return session.getId() + "," + username + ",端口" + request.getLocalPort();}@PostMapping("/checkTeacher")public String checkteacher(String teacherName) {// SpringBoot操作RedisString lockKey = "lockKey";RLock redissonLock = null;String num = "";try {redissonLock = redisson.getLock("lockKey");//加锁redissonLock.tryLock(30, TimeUnit.SECONDS);//超时时间:每间隔10秒(1/3)num = stringRedisTemplate.opsForValue().get(teacherName);int n = Integer.parseInt(num);if (n > 0) {n = n - 1;stringRedisTemplate.opsForValue().set("lkz", n + "");//正常选择老师System.out.println("当前名额:" + n);} else {return "名额已满";}} catch (InterruptedException e) {e.printStackTrace();} finally {redissonLock.unlock();//释放锁}return num;}// @PostMapping("/checkTeacher")// public String checkteacher(String teacherName) {//     InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH);//     String num = "";//     try {//         if (lock.acquire(6000, TimeUnit.SECONDS)) {//             // System.out.println("拿到了锁");//             //业务逻辑//             num = stringRedisTemplate.opsForValue().get(teacherName);//             int n = Integer.parseInt(num);//             if (n > 0) {//                 n = n - 1;//                 stringRedisTemplate.opsForValue().set("lkz", n + "");//                 //正常选择老师//                 System.out.println("当前名额:" + n);//             } else {//                 return "名额已满";//             }//             // System.out.println("任务完毕,该释放锁了");//         }//     } catch (Exception e) {//         System.out.println("业务异常");//         e.printStackTrace();//     }finally {//         try {//             lock.release();//         } catch (Exception e) {//             System.out.println("释放锁异常");//             e.printStackTrace();//         }//     }//     return num;// }
}
  • redis需要有对应的key
set lkz 6

 

1.3 启动项目

  • 第一步:启动redis,并且给lkz赋值
  • 第二步:启动nginx,nginx需要做配置,指向本地的8000和9000端口
upstream testdev{server   127.0.0.1:8000 weight=1;server   127.0.0.1:9000 weight=1;}server {listen       80;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;proxy_pass http://testdev;proxy_redirect default;}
  • 第三步:idea中启动8000端口,并且再修改配置文件端口,再启动9000端口

点击这个,然后修改9000即可同时启动8000和9000端口

  • 第三步:启动Jmeter,发请求

 

 

1.4 结果

Redission的结果自行查看,博主偷懒了在下面的zookeeper实现分布式锁的结果才截图了。

2、Zookeeper实现分布式锁

2.1 前提准备

  • 下载好nginx(windows版本)
  • 下载好Jmeter(模仿高并发)
  • 下载好redis(windows版)
  • 下载好zookeeper(windows版本)和ZooInspector(可视化工具,也可以不下载)

2.2 代码

  • pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.2</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>cn.lanqiao</groupId><artifactId>arcdemo</artifactId><version>0.0.1-SNAPSHOT</version><name>arcdemo</name><description>arcdemo</description><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- redisson --><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.17.5</version></dependency><!--    zookeeper和curator--><dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>3.5.7</version></dependency><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></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
  • controller
package com.example.controller;import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;/*** @Author Devere19* @Date 2022/8/17 10:41* @Version 1.0*/
@RestController
public class BiSheController {private static final String ZK_ADDRESS = "127.0.0.1:2181";private static final String ZK_LOCK_PATH = "/zkLock";static CuratorFramework client = null;static {//连接zkclient = CuratorFrameworkFactory.newClient(ZK_ADDRESS,new RetryNTimes(10, 5000));client.start();}// 分布式锁// @Autowired// private Redisson redisson;@Resourceprivate StringRedisTemplate stringRedisTemplate;@GetMapping("/login")public String login(String username, HttpSession session, HttpServletRequest request) {session.setAttribute("username", username);return username + ",端口" + request.getLocalPort();}@GetMapping("/getUser")public String getUser(HttpSession session, HttpServletRequest request) {String username = (String) session.getAttribute("username");return session.getId() + "," + username + ",端口" + request.getLocalPort();}// @PostMapping("/checkTeacher")// public String checkteacher(String teacherName) {//     // SpringBoot操作Redis//     String lockKey = "lockKey";//     RLock redissonLock = null;//     String num = "";//     try {//         redissonLock = redisson.getLock("lockKey");//加锁//         redissonLock.tryLock(30, TimeUnit.SECONDS);//超时时间:每间隔10秒(1/3)//         num = stringRedisTemplate.opsForValue().get(teacherName);//         int n = Integer.parseInt(num);////         if (n > 0) {//             n = n - 1;//             stringRedisTemplate.opsForValue().set("lkz", n + "");//             //正常选择老师//             System.out.println("当前名额:" + n);//         } else {//             return "名额已满";//         }//     } catch (InterruptedException e) {//         e.printStackTrace();//     } finally {//         redissonLock.unlock();//释放锁//     }//     return num;// }@PostMapping("/checkTeacher")public String checkteacher(String teacherName) {InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH);String num = "";try {if (lock.acquire(6000, TimeUnit.SECONDS)) {// System.out.println("拿到了锁");//业务逻辑num = stringRedisTemplate.opsForValue().get(teacherName);int n = Integer.parseInt(num);if (n > 0) {n = n - 1;stringRedisTemplate.opsForValue().set("lkz", n + "");//正常选择老师System.out.println("当前名额:" + n);} else {return "名额已满";}// System.out.println("任务完毕,该释放锁了");}} catch (Exception e) {System.out.println("业务异常");e.printStackTrace();}finally {try {lock.release();} catch (Exception e) {System.out.println("释放锁异常");e.printStackTrace();}}return num;}
}

2.3 启动项目

  • 第一步:启动redis,并且给lkz赋值
  • 第二步:启动nginx,nginx需要做配置,指向本地的8000和9000端口
upstream testdev{server   127.0.0.1:8000 weight=1;server   127.0.0.1:9000 weight=1;}server {listen       80;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;proxy_pass http://testdev;proxy_redirect default;}
  • 第三步:idea中启动8000端口,并且再修改配置文件端口,再启动9000端口

点击这个,然后修改9000即可同时启动8000和9000端口

  • 第三步:启动zookeeper,并且启动ZooInspector可视化工具
  • 第四步:启动Jmeter,发请求

 

2.4 结果 

 

看到控制台的输出,可以看出来分布式锁起作用了,并且可以观看ZooInspector进行查看 

因为这里采用的是有序临时锁,所以请求发完之后就删除了锁。必须在发起请求的一瞬间去刷新,才可能看到排好序的锁。 


http://chatgpt.dhexx.cn/article/IsuWtYnG.shtml

相关文章

Zookeeper 客户端之基本操作指令

ZooKeeper命令行工具类似于Linux的shell环境&#xff0c;不过功能肯定不及shell啦&#xff0c;但是使用它我们可以简单的对ZooKeeper进行访问&#xff0c;数据创建&#xff0c;数据修改等操作. 命令行工具的一些简单操作如下&#xff1a; zkCli.sh客户端连接命令 ls 与 ls2 命…

kafka内置zookeeper启动失败报错INFO ZooKeeper audit is disabled. (org.apache.zookeeper.audit.ZKAuditProvider)

kafka内置zookeeper启动失败报错INFO ZooKeeper audit is disabled.(org.apache.zookeeper.audit.ZKAuditProvider)2022年新版win10安装kafka 安装配置kafka&#xff0c;在启动zookeeper时报错ZooKeeper audit is disabled 原因分析&#xff1a; 寻找资料发现是zookeeper设置参…

zookeeper日志及快照清理操作

事务日志可视化转换 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #!/bin/sh # scriptname: zkLog2txt.sh # zookeeper事务日志为二进制格式&#xff0c;使用LogFormatter方法转换为可阅读的日志 if [ -z "$1" -o "$1" "-h&quo…

【RPC】注册中心实现方案之ZooKeeper

文章目录 ZooKeeper一致性协议&#xff1a;ZAB ZooKeeper ZooKeeper是一个开源的分布式协调服务&#xff0c;它可以用来协调和同步多服务器之间的状态。 ZooKeeper 可以作为微服务架构中注册中心的选型&#xff0c;它最需要被关心的也是数据模型和一致性协议。数据模型关乎服…

Linux 搭建zookpeer集群和配置

zookpeer和JDK1.8下载地址 下载地址&#xff1a;zookpeer和jdk1.8 提取码&#xff1a;w189 解压以及配置zookpeer tar -zxvf zookeeper-3.4.6.tar.gz tar -zxvf jdk-8u144-linux-x64.tar.gz 基本参数配置 参数描述clientPort主要定义客户端连接zookeeper server的端口&…

hadoop-zookeeper的详细介绍以及安装配置步骤

一、zookeeper的介绍 ZooKeeper是一个分布式的&#xff0c;开放源码的分布式应用程序协调服务&#xff0c;是Google的Chubby一个开源的实现&#xff0c;是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件&#xff0c;提供的功能包括&#xff1a;配置维护、…

k8s-7: kafka+zookeeper的单节点与集群的持久化

之前在k8s环境中有这个需求&#xff0c;看了好多的文档&#xff0c;都有坑&#xff0c;踩了一边总结一下&#xff0c;需要的朋友可自取 一、单节点部署 建议开发环境使用&#xff0c;且此处采用动态挂载的&#xff0c;生产不建议 1、安装zk cat > zk.yaml <<EOF a…

Docker 安装Zookeeper

第一步&#xff1a;查看本地镜像和检索拉取Zookeeper 镜像 # 查看本地镜像 docker images # 检索ZooKeeper 镜像 docker search zookeeper # 拉取ZooKeeper镜像最新版本 docker pull zookeeper:latest [rootlocalhost ~]# docker images REPOSITORY TAG …

mac pro m1:搭建zookeeper集群并设置开机自启

0. 引言 之前我们讲解过搭建zookeeper单节点&#xff0c;但在实际生产中&#xff0c;为了保证服务高可用&#xff0c;通常我们是采用集群模式。所以本次我们来实操集群模式的搭建 1. zk集群模式 zk可以作为注册中心和配置中心&#xff0c;常用在微服务各类组件的多节点服务治…

一款实用的数据恢复软件—zook data recovery wizard

zook data recovery wizard是RecoveryTools下的一款子品牌&#xff0c;同时也是一款功能实用的数据恢复软件&#xff0c;该软件可以从Windows中恢复已删除&#xff0c;损坏&#xff0c;格式化和丢失的数据&#xff0c;能够支持从驱动器&#xff0c;SD卡&#xff0c;硬盘&#x…

zook 报错 Unable to read additional data from server sessionid 0x0

zook报错启动报错&#xff1a; 2017-09-25 18:33:46,913 - INFO [main-SendThread(localhost:2181):ClientCnxn$SendThread1183] - Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting r…

hadoop大数据集群搭设(hadoop+zook+HBase+hive)百分百成功

hadoop大数据集群搭设 前言所需软件虚拟机准备工作一、Jdk安装二、安装zookeeper三、HBase安装四、mysql安装配置五、安装hive 前言 经过长时间的测试总结出在目前集群搭建最稳定的步骤是&#xff1a; 至少我按这个过程基本0失误&#xff0c;且初始化次数最少。当然也可以尝试…

zookeeper客户端命令(三)

zookeeper客户端命令&#xff08;三&#xff09; 问题背景zookeeper分布式技术基本概念&#xff08;一&#xff09;zookeeper单机及集群部署&#xff0c;附安装包下载&#xff08;二&#xff09;zookeeper客户端命令&#xff08;三&#xff09; zook客户端指令节点创建测试集群…

Zookper集群搭建

&#x1f345;程序员小王的博客&#xff1a;程序员小王的博客 &#x1f345; 欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; &#x1f345; 如有编辑错误联系作者&#xff0c;如果有比较好的文章欢迎分享给我&#xff0c;我会取其精华去其糟粕 一、搭建zookper集群前的准备…

分布式系统服务框架Zookeeper介绍与原理实现

分布式数据管理之痛点 为了确保微服务之间松耦合&#xff0c;每个服务都有自己的数据库, 有的是关系型数据库&#xff08;SQL&#xff09;&#xff0c;有的是非关系型数据库&#xff08;NoSQL&#xff09;。 开发企业事务往往牵涉到多个服务&#xff0c;要想做到多个服务数据…

给视频加滚动字幕,给视频加字幕制作mv 录制的视频配背景音乐

给视频添加滚动字幕方法其实很简单&#xff0c;像我们下载的电影&#xff0c;歌曲&#xff0c;用手机录制的视频都可以加字幕&#xff0c;或者滚动字幕&#xff0c;也可以加背景音乐或其它声音&#xff0c;给视频开头或结尾加一张图片或多张图片等等都是可以实现的&#xff0c;…

手把手叫你制作一个精美的在线音乐播放器

最近项目中要增加一些特殊的功能&#xff0c;实现音乐的在线播放。虽说网上源码一大把&#xff0c;demo一大堆&#xff0c;但是能用的其实寥寥无几&#xff0c;看来关键时刻还是自己动手&#xff0c;丰衣足食啊。话不多说&#xff0c;直接看效果图吧&#xff1a; 看是不是很美观…

微信小程序中将图片与音乐制作成MV

最近一直在开发一个类似于小年糕的微信小程序&#xff0c;在开发制作MV功能时 &#xff0c;花费了一些心思&#xff0c;其间主要遇到了以下一些问题点&#xff1a; 1. 上传图片的动画效果如何像播放视频一样实现播放与暂停&#xff1f; 2. 用户上传的图片数量不确定&#xf…

FL Studio中文版21最新免费音乐编曲软件制作工具

FL Studio较为适合专业的音乐制作者&#xff0c;操作难度较大&#xff0c;学习门槛也较高&#xff1b;Studio One则主打一站式的音乐制作&#xff0c;从编曲到录音到后期的专辑制作都可以在其中实现&#xff0c;同时操作难度不大&#xff0c;对初学者和业余爱好者都较为友好。 …

mv

mv 移动文件或改名 mv 命令&#xff08;move 的缩写&#xff09;&#xff0c;既可以在不同的目录之间移动文件或目录&#xff0c;也可以对文件和目录进行重命名。 该命令的基本格式如下&#xff1a; [rootlocalhost ~]# mv 【选项】 源文件 目标文件“mv” 默认执行命令(mv -…