近来需要做一个优惠券的功能,因优惠券是有数量限制的,所以想到了用redis的分布式锁来实现库存的变更,当然,也可以用到商品的库存变更。
首先,为了确保分布式锁可用,我们至少要确保锁的实现同时满足以下四个条件:
- 互斥性。在任意时刻,只有一个客户端能持有锁。
- 不会发生死锁。即使有一个客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其他客户端能加锁。
- 具有容错性。只要大部分的Redis节点正常运行,客户端就可以加锁和解锁。
- 加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了。
下面是redis分布式锁的工具类
@Component
public class RedisLock {
private Logger logger = LoggerFactory.getLogger(RedisLock.class);
@Autowired(required = false)
private StringRedisTemplate redisTemplate;
private static final String RELEASE_SUCCESS = "1";
private static final String UNLOCK_LUA;
private static final String LOCK_LUA;
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] then");
sb.append(" return tostring(redis.call(\"del\",KEYS[1])) ");
sb.append("else ");
sb.append(" return \"0\" ");
sb.append("end ");
UNLOCK_LUA = sb.toString();
}
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"set\",KEYS[1],ARGV[1],\"NX\",\"PX\",ARGV[2])");
sb.append("then ");
sb.append(" return \"1\" ");
sb.append("else ");
sb.append(" return \"0\" ");
sb.append("end ");
LOCK_LUA = sb.toString();
}
private static final StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//private StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();
/**
* 上锁
*/
public boolean lock(String key, String requestId, int retryTimes, String expireTime) {
if (retryTimes <= 0)
retryTimes = 1;
try {
int count = 0;
while (true) {
// 执行set命令
DefaultRedisScript<String> stringDefaultRedisScript = lockRedisScript();
String absent = redisTemplate.execute(stringDefaultRedisScript, stringRedisSerializer, stringRedisSerializer, Collections.singletonList(key), requestId, expireTime);
//是否成功获取锁
if (RELEASE_SUCCESS.equals(String.valueOf(absent))) {
return true;
} else {
count++;
if (retryTimes == count) {
logger.warn("has tried {} times , failed to acquire lock for key:{},requestId:{}", count, key, requestId);
return false;
} else {
logger.warn("try to acquire lock {} times for key:{},requestId:{}", count, key, requestId);
Thread.sleep(100);
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
/**
* 解锁
*/
public boolean unlock(String key, String requestId) {
//使用Lua脚本:先判断是否是自己设置的锁,再执行删除
DefaultRedisScript<String> stringDefaultRedisScript = unLockRedisScript();
String result = redisTemplate.execute(stringDefaultRedisScript, stringRedisSerializer, stringRedisSerializer, Collections.singletonList(key), requestId);
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}
@Bean
public DefaultRedisScript<String> unLockRedisScript() {
DefaultRedisScript<String> defaultRedisScript = new DefaultRedisScript<>();
defaultRedisScript.setResultType(String.class);
defaultRedisScript.setScriptText(UNLOCK_LUA);
// defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("delete.lua")));
return defaultRedisScript;
}
@Bean
public DefaultRedisScript<String> lockRedisScript() {
DefaultRedisScript<String> defaultRedisScript = new DefaultRedisScript<>();
defaultRedisScript.setResultType(String.class);
defaultRedisScript.setScriptText(LOCK_LUA);
// defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("delete.lua")));
return defaultRedisScript;
}
}
业务中的实现逻辑
Object sto = redisCacheUtil.getCacheObject(CouponConstant.REDIS_COUPON_STOCK + userCouponDto.getfCouponId().toString());
Integer stoNum;
if (!StringUtils.isEmpty(sto)) {
stoNum = Integer.parseInt(sto.toString());
} else {
//获取当前优惠券剩余数
stoNum = couponBean.getfGrantNum() - couponBean.getfIssuedNum();
redisCacheUtil.setCacheObject(CouponConstant.REDIS_COUPON_STOCK + userCouponDto.getfCouponId().toString(), stoNum + "", 30L);
}
String requestId = UUID.randomUUID().toString();
if (stoNum > 0) {
while (true) { //这里循环操作,以确保该线程一定获得锁并执行线程任务
int retryTimes = 3; //重试次数
String expireTime = "1000"; //过期时间
if (redisLock.lock(CouponConstant.REDIS_COUPON_LOCK + userCouponDto.getfCouponId().toString(), requestId, retryTimes, expireTime)) {
try { //加其为避免库存超量
stoNum--;
CouponBean coupon = new CouponBean();
coupon.setfId(userCouponBean.getfCouponId());
coupon.setfIssuedNum(couponBean.getfGrantNum() - stoNum);
int j = couponService.updateByPrimaryKeySelective(coupon);
if (j != 0) {
redisCacheUtil.setCacheObject(CouponConstant.REDIS_COUPON_STOCK + userCouponDto.getfCouponId().toString(), stoNum + "", 30L);
}
} finally {
boolean unlock = redisLock.unlock(CouponConstant.REDIS_COUPON_LOCK+userCouponDto.getfCouponId().toString(), requestId);
if (unlock) {
logger.info("-------解锁成功-----");
}
}
break;
}
}
}
在用多线程的测试中,测试成功
@GetMapping(value = "/testLock")
public void testLock() {
UserCouponDto userCouponBean = new UserCouponDto();
long l = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Thread thread = new Thread(() -> {
userCouponBean.setfCouponId(1L);
Map<String, Object> map = ShopCouponReceive(userCouponBean);
});
thread.run();
}
System.out.println("------------costTime" + (System.currentTimeMillis() - l));
}