20220508_Redisson分布式锁库存扣减学习笔记
1概述
本文主要学习一下下面的知识点:
- 普通商品数量的扣减
- 高并发场景下分布式锁Redisson的使用确保商品独占访问
- 结合Lua脚本原子性进行商品扣库存(判断库存数量与库存扣减放在一起执行,避免检测到有库存,然后扣的时候,已经卖完了的超卖现象)
2代码示例
模仿高并发场景下,三个商品,100任务去扣减,每个任务扣减数量为:1。最终只有3个能成功。
2.1pom依赖
<!--1.spring-boot-starter-web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--2.spring-boot-starter-test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--3.redisson-spring-boot-starter分布式锁-->
<!--最好引用2.13.0 至 3.11.5版本的 redisson-spring-boot-starter-->
<!--内置 starter-data-redis,RedisAutoConfiguration 类-->
<!--org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\-->
<!--org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\-->
<!--org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<!--<version>3.13.1</version>-->
<version>3.11.5</version>
</dependency>
2.2MyRedisConfig
package com.kikop.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;
/**
* @author kikop
* @version 1.0
* @project myredissiondemo
* @file MyRedisConfig
* @desc MyRedisConfig配置类
* @date 2021/3/30
* @time 8:00
* @by IDE IntelliJ IDEA
*/
@Configuration
public class MyRedisConfig {
@Value("${com.kikop.lua.srcript.name}")
private String mygoodsdecy;
/**
* 配置 RedisTemplate模板
* 指定连接工厂,数据序列化等关键属性
*
* @param redisConnectionFactory RedisConnectionFactory怎么由来的源码分析 todo
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 1.构建 redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// 1.1.配置连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
//1.2.构建ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
// 指定要序列化的域,field,get和set,
// 以及修饰符范围,ANY是都有包括 private和public
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如 String,Integer等会抛出异常
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // 2.1.x
// objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); // 2.2.x
// 1.3.使用Jackson2JsonRedisSerializer来序列化和反序列化
// redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
jacksonSeial.setObjectMapper(objectMapper);
// 1.4.序列化kv
// 使用 StringRedisSerializer来序列化和反序列化redis的key值
redisTemplate.setKeySerializer(new StringRedisSerializer());
// 值采用json序列化
redisTemplate.setValueSerializer(jacksonSeial);
// 1.5.序列化hash kv
// 设置hash key 和value序列化模式
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(jacksonSeial);
// 1.6.afterPropertiesSet
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* dataStruct:String
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, String> stringOperations(StringRedisTemplate redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对POJO类型序列化和反序列化操作
* 存储还是以JSON字符串形式
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* dataStruct:hash
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* dataStruct:list
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* dataStruct:set
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* dataStruct:zset
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
/**
* DefaultRedisScript
* 读取限流脚本
* spring-data-redis.jar
*
* @return
*/
@Bean
public DefaultRedisScript<Number> defaultRedisScript() {
DefaultRedisScript<Number> redisScript = new DefaultRedisScript<>();
// 1.限流脚本位置
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(mygoodsdecy)));
// 2.Lua脚本返回类型
redisScript.setResultType(Number.class);
return redisScript;
}
}
2.3RedissionConfig
package com.kikop.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author kikop
* @version 1.0
* @project Name: myredissiondemo
* @file RedissionConfig
* @desc RedissonApplication启动类(配置类)
* https://www.jianshu.com/p/59ffff18e1ff
* @date 2021/3/30
* @time 8:00
* @by IDE IntelliJ IDEA
*/
@Configuration
public class RedissionConfig {
@Autowired
private RedisProperties redisProperties;
/**
* 单机模式
* 构建 RedissonClient
* 容器总的Bean名称即为:方法名 redissonClient
* @return
*/
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
// config.useSingleServer().setAddress("redis://ip:port")
// .setPassword("password")
// .setDatabase(0);
String redisAddress = "redis://" + redisProperties.getHost() + ":" + redisProperties.getPort();
config.useSingleServer().setAddress(
// String.format("redis://%s:%s", redisProperties.getHost(), redisProperties.getPort())
redisAddress
)
.setDatabase(0);
RedissonClient redissonClient = Redisson.create(config);
return redissonClient;
}
// /**
// * 哨兵模式
// * 构建 RedissonClient
// *
// * @return
// */
//// @Bean
// public RedissonClient sentinelRedissonClient() {
// Config config = new Config();
// config.useSentinelServers().addSentinelAddress("redis://ip1:port1",
// "redis://ip2:port2",
// "redis://ip3:port3")
// .setMasterName("mymaster")
// .setPassword("password")
// .setDatabase(0);
// RedissonClient redissonClient = Redisson.create(config);
// return redissonClient;
// }
//
// /**
// * Cluster集群模式
// * 构建 RedissonClient
// *
// * @return
// */
//// @Bean
// public RedissonClient clusterRedissonClient() {
// Config config = new Config();
// ClusterServersConfig clusterServersConfig = config.useClusterServers()
// .setPassword(redisProperties.getPassword())
// .setScanInterval(5000);
//
// // 注册集群各个节点
// for (String node : redisProperties.getCluster().getNodes()) {
// clusterServersConfig.addNodeAddress("redis://".concat(node));
// }
// RedissonClient redissonClient = Redisson.create(config);
// return redissonClient;
// }
}
2.4mygoodsdecy脚本
-- lua脚本进行原子商品扣库存操作
-- 返回值,0:失败;1:成功
-- 由于lua脚本接收到参数都会转为String,所以要转成数字类型才能比较
-- 参数1:商品的key
local key = KEYS[1]
-- 参数2:扣除库存数量
local amount = tonumber(ARGV[1])
-- 若 key 存在,返回 1 ,否则返回 0
if redis.call('exists',key) == 0 then -- key不存在
return 0
else
-- 当前的库存总量
-- 返回 key 所关联的字符串值。
-- 如果 key 不存在那么返回特殊值 nil 。
-- 假如 key 储存的值不是字符串类型,返回一个错误,因为 GET 只能用于处理字符串值。
local totalamount = tonumber(redis.call('get',key))
if(amount <= totalamount) then -- 逻辑校验,防止超卖
redis.call('decrby',key,amount)
return 1
end
return 0
end
2.5业务实现
2.5.1模拟商品加载
/**
* 加载商品XXX库存入缓存
*
* @param key_goods_001
*/
private void loadGoodsInfo(String key_goods_001) {
// 库存总量
int gogal_totalamountLimit = 3;
// 初始化Redis缓存,数据类型:String
// 1.从数据库加载来的,10秒的过期时间
// stringRedisTemplate.opsForValue().set(
// key_goods_001,String.valueOf(gogal_totalamountLimit),10,TimeUnit.SECONDS);
// 2.从数据库加载来的,设置永不过期
// stringRedisTemplate.opsForValue().setIfAbsent(key_goods_001, String.valueOf(gogal_totalamountLimit));
stringRedisTemplate.opsForValue().set(key_goods_001, String.valueOf(gogal_totalamountLimit));
}
2.5.2商品库存扣减
2.5.2.1商品库存扣减实现方案1
/**
* 商品库存扣减实现方案1
* 缺点:判断与扣减放在两个地方,无法保证原子性
* 即使增加对库存总量的判断,容易出现商品负数倒卖
*
* @param lock_goods_001
* @param key_goods_001
* @param descAmount https://blog.csdn.net/qq_41534566/article/details/79219023
*/
public void descryGoodsNoLock(String lock_goods_001, String key_goods_001, int descAmount) {
try {
// 3.库存扣减业务操作
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "开始扣库存...");
String currentAmount = stringRedisTemplate.opsForValue().get(key_goods_001);
// 3.1方法一
// 判断与扣减放在两个地方,无法保证原子性
// 即使增加对库存总量的判断,容易出现商品负数倒卖
if (descAmount <= Integer.valueOf(currentAmount)) { // 判断
stringRedisTemplate.opsForValue().decrement(key_goods_001, descAmount); // 扣减
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "恭喜你,买到大宝贝了,扣库存成功!");
} else {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "大宝贝卖完了,扣库存失败!");
}
// 4.库存查询
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "当前库存剩余数量:" + currentAmount);
} finally {
}
}
2.5.2.2商品库存扣减实现方案2
/**
* 商品库存扣减实现方案2
* 增加RedissonLock分布式锁
*
* @param lock_goods_001
* @param key_goods_001
* @param descAmount https://blog.csdn.net/qq_41534566/article/details/79219023
*/
public void descryGoodsByLock(String lock_goods_001, String key_goods_001, int descAmount) {
RLock rLock = null;
try {
// 1.构建锁 RLock
// 如场景:
// 过独木桥,
// 发票卡口。
rLock = redissonClient.getLock(lock_goods_001);
// 2.获取某任务锁 by lua,如果获取不到锁,则一直阻塞(对比tryLock)
// 内置自动续命的功能,leaseTime:-1
rLock.lock();
// 3.库存扣减业务操作
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "开始扣库存...");
String currentAmount = stringRedisTemplate.opsForValue().get(key_goods_001);
// 3.1方法一
// 判断与扣减放在两个地方,无法保证原子性
// 缺少对库存总量的判断,容易出现商品负数倒卖
if (descAmount <= Integer.valueOf(currentAmount)) { // 判断
stringRedisTemplate.opsForValue().decrement(key_goods_001, descAmount); // 扣减
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "恭喜你,买到大宝贝了,扣库存成功!");
} else {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "大宝贝卖完了,扣库存失败!");
}
// 4.库存查询
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "当前库存剩余数量:" + currentAmount);
} finally {
if (rLock != null && rLock.isHeldByCurrentThread()) {
rLock.unlock();
}
}
}
2.5.2.3商品库存扣减实现方案3
/**
* 商品库存扣减实现方案3
* 增加RedissonLock分布式锁、扣减库存通过Lua脚本执行
*
* @param lock_goods_001
* @param key_goods_001
* @param descAmount https://blog.csdn.net/qq_41534566/article/details/79219023
*/
public void descryGoodsByLockAndLua(String lock_goods_001, String key_goods_001, int descAmount) {
RLock rLock = null;
try {
// 1.构建锁 RLock
// 如场景:
// 过独木桥,
// 发票卡口。
rLock = redissonClient.getLock(lock_goods_001);
// 2.获取某任务锁 by lua,如果获取不到锁,则一直阻塞(对比tryLock)
// 内置自动续命的功能,leaseTime:-1
rLock.lock();
// 3.库存扣减业务操作
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "开始扣库存...");
String currentAmount = stringRedisTemplate.opsForValue().get(key_goods_001);
// 3.2.方法二
// 解决办法:
// 判断是否有余量库存与扣除动作保持原子性,放在lua脚本里即可。
List<String> keys = Arrays.asList(key_goods_001);
Number execResult = stringRedisTemplate.execute(defaultRedisScript, keys, String.valueOf(descAmount));
if (null == execResult || execResult.intValue() == 0) {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "大宝贝卖完了,扣库存失败!");
} else {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "恭喜你,买到大宝贝了,扣库存成功!");
}
// 4.库存查询
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "当前库存剩余数量:" + currentAmount);
} finally {
if (rLock != null && rLock.isHeldByCurrentThread()) {
rLock.unlock();
}
}
}
2.6完整代码及测试
package com.kikop;
import com.kikop.util2.MyDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
/**
* @author kikop
* @version 1.0
* @project myredissiondemo
* @file RedissonApplicationTests
* @desc
* @date 2021/3/30
* @time 8:00
* @by IDE IntelliJ IDEA
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class GoodRepoApplicationTest {
// 1.访问商品库存的锁
@Autowired
private RedissonClient redissonClient;
// 2.操作商品库存扣减
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
private DefaultRedisScript<Number> defaultRedisScript;
// Redisson分布式锁
// 对应 某具体商品XXX
private final String LOCK_GOODS_ADD_PREFIX = "lock:goods:decry:";
// 对应某具体商品XXX的库存key
private final String KEY_GOODS_ADD_PREFIX = "key:goods:";
/**
* 加载商品XXX库存入缓存
*
* @param key_goods_001
*/
private void loadGoodsInfo(String key_goods_001) {
// 库存总量
int gogal_totalamountLimit = 3;
// 初始化Redis缓存,数据类型:String
// 1.从数据库加载来的,10秒的过期时间
// stringRedisTemplate.opsForValue().set(
// key_goods_001,String.valueOf(gogal_totalamountLimit),10,TimeUnit.SECONDS);
// 2.从数据库加载来的,设置永不过期
// stringRedisTemplate.opsForValue().setIfAbsent(key_goods_001, String.valueOf(gogal_totalamountLimit));
stringRedisTemplate.opsForValue().set(key_goods_001, String.valueOf(gogal_totalamountLimit));
}
/**
* 商品库存扣减实现方案1
* 缺点:判断与扣减放在两个地方,无法保证原子性
* 即使增加对库存总量的判断,容易出现商品负数倒卖
*
* @param lock_goods_001
* @param key_goods_001
* @param descAmount https://blog.csdn.net/qq_41534566/article/details/79219023
*/
public void descryGoodsNoLock(String lock_goods_001, String key_goods_001, int descAmount) {
try {
// 3.库存扣减业务操作
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "开始扣库存...");
String currentAmount = stringRedisTemplate.opsForValue().get(key_goods_001);
// 3.1方法一
// 判断与扣减放在两个地方,无法保证原子性
// 即使增加对库存总量的判断,容易出现商品负数倒卖
if (descAmount <= Integer.valueOf(currentAmount)) { // 判断
stringRedisTemplate.opsForValue().decrement(key_goods_001, descAmount); // 扣减
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "恭喜你,买到大宝贝了,扣库存成功!");
} else {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "大宝贝卖完了,扣库存失败!");
}
// 4.库存查询
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "当前库存剩余数量:" + currentAmount);
} finally {
}
}
/**
* 商品库存扣减实现方案2
* 增加RedissonLock分布式锁
*
* @param lock_goods_001
* @param key_goods_001
* @param descAmount https://blog.csdn.net/qq_41534566/article/details/79219023
*/
public void descryGoodsByLock(String lock_goods_001, String key_goods_001, int descAmount) {
RLock rLock = null;
try {
// 1.构建锁 RLock
// 如场景:
// 过独木桥,
// 发票卡口。
rLock = redissonClient.getLock(lock_goods_001);
// 2.获取某任务锁 by lua,如果获取不到锁,则一直阻塞(对比tryLock)
// 内置自动续命的功能,leaseTime:-1
rLock.lock();
// 3.库存扣减业务操作
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "开始扣库存...");
String currentAmount = stringRedisTemplate.opsForValue().get(key_goods_001);
// 3.1方法一
// 判断与扣减放在两个地方,无法保证原子性
// 缺少对库存总量的判断,容易出现商品负数倒卖
if (descAmount <= Integer.valueOf(currentAmount)) { // 判断
stringRedisTemplate.opsForValue().decrement(key_goods_001, descAmount); // 扣减
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "恭喜你,买到大宝贝了,扣库存成功!");
} else {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "大宝贝卖完了,扣库存失败!");
}
// 4.库存查询
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "当前库存剩余数量:" + currentAmount);
} finally {
if (rLock != null && rLock.isHeldByCurrentThread()) {
rLock.unlock();
}
}
}
/**
* 商品库存扣减实现方案3
* 增加RedissonLock分布式锁、扣减库存通过Lua脚本执行
*
* @param lock_goods_001
* @param key_goods_001
* @param descAmount https://blog.csdn.net/qq_41534566/article/details/79219023
*/
public void descryGoodsByLockAndLua(String lock_goods_001, String key_goods_001, int descAmount) {
RLock rLock = null;
try {
// 1.构建锁 RLock
// 如场景:
// 过独木桥,
// 发票卡口。
rLock = redissonClient.getLock(lock_goods_001);
// 2.获取某任务锁 by lua,如果获取不到锁,则一直阻塞(对比tryLock)
// 内置自动续命的功能,leaseTime:-1
rLock.lock();
// 3.库存扣减业务操作
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "开始扣库存...");
String currentAmount = stringRedisTemplate.opsForValue().get(key_goods_001);
// 3.2.方法二
// 解决办法:
// 判断是否有余量库存与扣除动作保持原子性,放在lua脚本里即可。
List<String> keys = Arrays.asList(key_goods_001);
Number execResult = stringRedisTemplate.execute(defaultRedisScript, keys, String.valueOf(descAmount));
if (null == execResult || execResult.intValue() == 0) {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "大宝贝卖完了,扣库存失败!");
} else {
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "恭喜你,买到大宝贝了,扣库存成功!");
}
// 4.库存查询
System.out.println(MyDateUtil.getCurrentDateStrByDefaultFormat() + "," + "当前库存剩余数量:" + currentAmount);
} finally {
if (rLock != null && rLock.isHeldByCurrentThread()) {
rLock.unlock();
}
}
}
@Test
public void testGoodsMiaoSha() throws InterruptedException {
// 根据商品ID控制商品锁的粒度要小
// XXX号商品锁(只是起个锁的名字)
String lock_goods_001 = LOCK_GOODS_ADD_PREFIX + "000001";
// XXX号商品在Redis缓存中的key
String key_goods_001 = KEY_GOODS_ADD_PREFIX + "000001";
loadGoodsInfo(key_goods_001);
int threads_num = 100;
CountDownLatch countDownLatch = new CountDownLatch(threads_num);
// 多个线程 forkJoinPool并发去获取锁
IntStream.range(0, threads_num).parallel().forEach(new IntConsumer() {
@Override
public void accept(int i) {
// 假设每次消耗库存数为1
int descAmount = 1;
GoodRepoApplicationTest.this.descryGoodsByLock(lock_goods_001, key_goods_001, descAmount);
countDownLatch.countDown();
}
});
// 等待任务执行完,主线程在退出
countDownLatch.await();
}
/**
* Lua脚本测试
*/
@Test
public void testGoodsDecryByLua() {
// XXX号商品在Redis缓存中的key
String key_goods_001 = KEY_GOODS_ADD_PREFIX + "000001";
// 假设每次消耗库存数为1
int descAmount = 1;
List<String> keys = Arrays.asList(key_goods_001);
Number execResult = stringRedisTemplate.execute(defaultRedisScript, keys, String.valueOf(descAmount));
System.out.println(execResult.intValue());
}
}
3总结
3.1方案2Redisson锁是否必要
必要,否则会出现方案1的商品超卖情况。
3.2方案3Redisson锁是否必要
不必要,因为Lua脚本已经控制了共享资源的独占访问,并且确保不会出现超卖现象。
网友评论