概要
redisson分布式锁
技术细节
引入Redisson包
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.4</version>
</dependency>
配置RedissonConfig
@Configuration
public class RedissonConfig {
@Value("${spring.redis2.host}")
private String redisHost;
@Value("${spring.redis2.port}")
private String redisPort;
@Value("${spring.redis2.password}")
private String redisPassword;
@Bean
public RedissonClient redisson() {
Config config = new Config();
if (StringUtils.isNotEmpty(redisPassword)) {
config.useSingleServer().setAddress("redis://" + redisHost + ":" + redisPort).setPassword(redisPassword);
}else {
config.useSingleServer().setAddress("redis://" + redisHost + ":" + redisPort);
}
return Redisson.create(config);
}
}
private static final String COUPON_LOCK_KEY = "coupon_lock:";
private static final String COUPON_STOCK_NUM = "coupon_stock_num:";
@Override
public void claimCoupon(String userId, String couponId) {
// 获取分布式锁
RLock rLock = redissonClient.getLock(COUPON_LOCK_KEY + couponId);
try {
rLock.lock();
// 执行领取优惠券的逻辑,例如更新数据库中的优惠券数量等
CouponInfo couponInfo = couponInfoMapper.selectById(couponId);
if (couponInfo == null) {
throw new JeecgBootException(COUPON_NO_EXITS);
}
this.checkCoupon(couponInfo, userId);
CouponUseInfo couponUseInfo = new CouponUseInfo();
couponUseInfo.setAppUserId(userId);
couponUseInfo.setShopId(couponInfo.getShopId());
couponUseInfo.setCouponId(couponInfo.getId());
couponUseInfo.setUseState(NO_USE);
couponUseInfo.setReceiveTime(new Date());
couponUseInfo.setShopUserId(couponInfo.getShopUserId());
//减库存
int stock = couponInfoMapper.reduceStock(couponId, couponInfo.getUseProvideNum());
if (stock == 1) {
if (redisTemplate.hasKey(COUPON_STOCK_NUM + couponInfo.getId())) {
redisTemplate.opsForValue().increment(COUPON_STOCK_NUM + couponInfo.getId(), -1);
}
if (redisTemplate.hasKey(SHOP_COUPON_NUM + couponInfo.getCouponType() + ":" + couponInfo.getShopId())) {
redisTemplate.opsForValue().increment(SHOP_COUPON_NUM + couponInfo.getCouponType() + ":" + couponInfo.getShopId(), -1);
}
//新增领取记录
couponUseInfoMapper.insert(couponUseInfo);
}
} finally {
//执行完毕释放锁。
rLock.unlock();
}
}
private void checkCoupon(CouponInfo couponInfo, String userId) {
//检查库存
if (couponInfo.getProvideNum() - couponInfo.getUseProvideNum() <= 0){
throw new JeecgBootException(COUPON_NO_STOCK);
}
//检查优惠券是否上架
if (!CHECK_SHTG.equals(couponInfo.getCheckState()) || !IS_GROUND.equals(couponInfo.getIsGrounding())){
throw new JeecgBootException(COUPON_NO_GROUND);
}
//检查用户领取该优惠券是否达到领取上限
Long couponCount = couponUseInfoMapper.selectCount(new QueryWrapper<CouponUseInfo>()
.eq("app_user_id",userId)
.eq("coupon_id",couponInfo.getId())
.eq("use_state",NO_USE));
if (couponCount >= couponInfo.getReceiveNumPerPeople()){
throw new JeecgBootException(COUPON_OUT_OF_LIMIT);
}
}
小结
通过这种方法也可以解决优惠券超发的问题。使用这种方法,无需关心key过期时间,加锁成功后会启动看门狗watch dag,默认会30s检查一下,如果当前锁被占用会自动对锁的过期时间进行延长。
可手动设置检测间隔时间
Config config = new Config();
config.setLockWatchdogTimeout();
最后一定要记得释放锁。