spring集成redisson实现分布式锁

2024-05-13 08:08

本文主要是介绍spring集成redisson实现分布式锁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在单进程的系统中,当存在多个线程可以同时改变某个变量(可变共享变量)时,就需要对变量或代码块做同步,使其在修改这种变量时能够线性执行消除并发修改变量。而Java提供的同步锁synchronized只能解决单台服务器上的并发问题,一般线上环境都是多台服务器部署同时运行,跨jvm的环境下synchronized的作用就不大了。这个时候redis就可以作为分布锁来使用了,一般都是基于redis setNx命令来实现自己的锁,建出来的键值一般都是有一个超时时间的(这个是Redis自带的超时特性),所以每个锁最终都会释放
这里介绍的是github上的一个开源项目,国外大神些的算法毕竟比自己实现的靠谱点项目源码地址,里面不光有分布锁,还有分布锁队列等等一系列模块
https://github.com/redisson/redissonpom.xml配置文件引人redisson相关包
<dependency><groupId>org.redisson</groupId><artifactId>redisson-all</artifactId><version>2.10.5</version>
</dependency>2. 配置方法2.1. 程序化配置方法Redisson程序化的配置方法是通过构建Config对象实例来实现的。例如:public class RedissonUtils {private static RedissonClient redissonClient;static{Config config = new Config();config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword(null);redissonClient = Redisson.create(config);}public static RedissonClient getRedisson(){return redissonClient;}public static void main(String[] args) throws InterruptedException{RLock fairLock = getRedisson().getLock("TEST_KEY");System.out.println(fairLock.toString());
//      fairLock.lock(); // 尝试加锁,最多等待10秒,上锁以后10秒自动解锁boolean res = fairLock.tryLock(10, 10, TimeUnit.SECONDS);System.out.println(res);fairLock.unlock();//有界阻塞队列
//      RBoundedBlockingQueue<JSONObject> queue = getRedisson().getBoundedBlockingQueue("anyQueue");// 如果初始容量(边界)设定成功则返回`真(true)`,// 如果初始容量(边界)已近存在则返回`假(false)`。
//      System.out.println(queue.trySetCapacity(10));
//      JSONObject o=new JSONObject();
//      o.put("name", 1);
//      if(!queue.contains(o)){
//          queue.offer(o);
//      }//      JSONObject o2=new JSONObject();
//      o2.put("name", 2);// 此时容量已满,下面代码将会被阻塞,直到有空闲为止。//      if(!queue.contains(o2)){
//          queue.offer(o2);
//      }//      //  获取但不移除此队列的头;如果此队列为空,则返回 null。
//      JSONObject obj = queue.peek();
//      //获取并移除此队列的头部,在指定的等待时间前等待可用的元素(如果有必要)。
//      JSONObject ob = queue.poll(10, TimeUnit.MINUTES);                                                    //获取并移除此队列的头,如果此队列为空,则返回 null。
//       Iterator<JSONObject> iterator=queue.iterator();
//       while (iterator.hasNext()){
//            JSONObject i =iterator.next();
//            System.out.println(i.toJSONString());
//            iterator.remove();
//          
//        }
//          while(queue.size()>0){
//              JSONObject ob = queue.poll();     
//              System.out.println(ob.toJSONString());
//          }
//      
//      JSONObject someObj = queue.poll();
//      System.out.println(someObj.toJSONString());}
2 spring集成的方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:redisson="http://redisson.org/schema/redisson" xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd  http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://redisson.org/schema/redissonhttp://redisson.org/schema/redisson/redisson.xsd"><context:component-scan base-package="component.controller.RedisServiceImpl" /><!-- redis连接池 -->  <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">          <property name="maxIdle" value="${redis_max_idle}"></property>   <property name="testOnBorrow" value="${redis_test_on_borrow}"></property>  </bean>  <!-- redis连接工厂 -->  <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  <property name="hostName" value="${redis_addr}"></property>  <property name="port" value="${redis_port}"></property>  <property name="password" value="${redis_auth}"></property>  <property name="poolConfig" ref="jedisConfig"></property>  </bean>  <!-- redis操作模板,这里采用尽量面向对象的模板 -->  <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  <property name="connectionFactory" ref="connectionFactory" />  <!--     如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->  <property name="keySerializer">  <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  </property>  <property name="valueSerializer">  <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  </property>  </bean>     <!--redisson配置的实例    单台redis机器配置    --><redisson:client id="redissonClient"><redisson:single-server address="redis://127.0.0.1:6379" connection-pool-size="30" />  </redisson:client>
</beans>引入RedissonClient就可以使用了
@Autowired  
private RedissonClient redissonClient;//获取redissson分布式锁RLock fairLock = redissonClient.getLock("TEST_KEY");       //尝试加锁 最多等待100秒 20秒后自动销毁
boolean res = fairLock.tryLock(100, 20, TimeUnit.SECONDS);//释放锁
fairLock.unlock();提醒:redis版本一定要3.0以上的 不然会报错,redis lua脚本

这篇关于spring集成redisson实现分布式锁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/985139

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Linux下删除乱码文件和目录的实现方式

《Linux下删除乱码文件和目录的实现方式》:本文主要介绍Linux下删除乱码文件和目录的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux下删除乱码文件和目录方法1方法2总结Linux下删除乱码文件和目录方法1使用ls -i命令找到文件或目录

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与