如何用redis来实现分布式锁
本篇内容主要讲解“如何用redis来实现分布式锁”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何用redis来实现分布式锁”吧!
创新互联建站从2013年创立,先为吉安等服务建站,吉安等地企业,进行企业商务咨询服务。为吉安企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
一、建Module
boot_redis01
boot_redis02
二、改POM
4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.4 com.lau boot_redis01 0.0.1-SNAPSHOT boot_redis01 Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 redis.clients jedis 3.1.0 org.springframework.boot spring-boot-starter-aop org.redisson redisson 3.13.4 org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true junit junit 4.12 org.springframework.boot spring-boot-maven-plugin
三、写YML
server.port=1111 spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379 #连接池最大连接数(使用负值表示没有限制)默认8 spring.redis.lettuce.pool.max-active=8 #连接池最大阻塞等待时间(使用负值表示没有限制)默认-1 spring.redis.lettuce.pool.max-wait=-1 #连接池中的最大空闲连接默认8 spring.redis.lettuce.pool.max-idle=8 #连接池中的最小空闲连接默认0 spring.redis.lettuce.pool.min-idle=0 ?
四、主启动
package com.lau.boot_redis01; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) public class BootRedis01Application { public static void main(String[] args) { SpringApplication.run(BootRedis01Application.class, args); } }
五、业务类
1、RedisConfig配置类
package com.lau.boot_redis01.config; import org.redisson.Redisson; import org.redisson.config.Config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.io.Serializable; @Configuration public class RedisConfig { @Value("${spring.redis.host}") private String redisHost; /** *保证不是序列化后的乱码配置 */ @Bean public RedisTemplateredisTemplate(LettuceConnectionFactory connectionFactory){ RedisTemplate redisTemplate =new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate; } @Bean public Redisson redisson(){ Config config = new Config(); config.useSingleServer().setAddress("redis://"+redisHost+":6379").setDatabase(0); return (Redisson) Redisson.create(config); } }
2、GoodController.java
package com.lau.boot_redis01.controller; import com.lau.boot_redis01.util.RedisUtil; import org.springframework.web.bind.annotation.RestController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import redis.clients.jedis.Jedis; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; @RestController public class GoodController { @Autowired private StringRedisTemplate stringRedisTemplate; @Value("${server.port}") private String serverPort; private static final String REDIS_LOCK = "atguigulock"; @GetMapping("/buy_goods") public String buy_Goods() throws Exception { String value = UUID.randomUUID().toString() + Thread.currentThread().getName(); try{ //1、key加过期时间是因为如果redis客户端宕机了会造成死锁,其它客户端永远获取不到锁 //2、这里将setnx与锁过期两条命令合二为一,是为了解决命令分开执行引发的原子性问题: //setnx 中间会被其它redis客户端命令加塞 2、expire //3①、为了避免线程执行业务时间大于锁过期时间导致窜行操作,再释放锁时应判断是否是自己加的锁; //还有另外一种解决方案:锁续期——额外开启一个守护线程定时给当前key加超时时间(如5s到期,每2.5s ttl判断一次,并加2.5s超时时间,不断续期,线程将使用主动删除key命令的方式释放锁;另,当此redis客户端命令宕机后,此守护线程会自动随之消亡,不会再主动续期——此机制使得其它redis客户端可以获得锁,不会发生死锁或长期等待) Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(REDIS_LOCK, value, 10L, TimeUnit.SECONDS);//setnx if(!flag){ return "获取锁失败!"; } String result = stringRedisTemplate.opsForValue().get("goods:001"); int goodsNumber = result == null ? 0 : Integer.parseInt(result); if (goodsNumber > 0){ int realNumber = goodsNumber - 1; stringRedisTemplate.opsForValue().set("goods:001",realNumber + ""); System.out.println("你已经成功秒杀商品,此时还剩余:" + realNumber + "件"+"\t 服务器端口: "+serverPort); return "你已经成功秒杀商品,此时还剩余:" + realNumber + "件"+"\t 服务器端口: "+serverPort; } System.out.println("商品已经售罄/活动结束/调用超时,欢迎下次光临"+"\t 服务器端口: "+serverPort); return "商品已经售罄/活动结束/调用超时,欢迎下次光临"+"\t 服务器端口: "+serverPort; } finally { // if(stringRedisTemplate.opsForValue().get(REDIS_LOCK).equals(value)){ // stringRedisTemplate.delete(REDIS_LOCK); // } //3②这里也存在命令的原子问题:获取当前key经相等判断后与删除对应key是两个不同命令,中间会被加塞 //解决方法1:redis事务 // stringRedisTemplate.watch(REDIS_LOCK); // while(true){ // if(stringRedisTemplate.opsForValue().get(REDIS_LOCK).equalsIgnoreCase(value)){ // stringRedisTemplate.setEnableTransactionSupport(true); // stringRedisTemplate.multi(); // stringRedisTemplate.delete(REDIS_LOCK); // // List