使用Redis實現分佈式下用戶鎖,主要使用redis的setIfAbsent和expire方法來實現,
例如:實現用戶抽獎功能,
主要代碼如下:
//抽獎
String randomStr = RandomUtils.nextInt(10000, 99999) + ":" + System.currentTimeMillis();
try {
String lockKey = "ActivityUser_"+userId;
//獲取鎖
boolean getLock = redisTemplate.opsForValue().setIfAbsent(lockKey, randomStr);
if (!getLock) {
return JsonResult.build(300010, "非法請求!");
}
//設置鎖過期時間
redisTemplate.expire(lockKey, 1, TimeUnit.MINUTES);
//開始進行業務操作.....省略
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Object lockObj = redisTemplate.opsForValue().get(lockKey);
if (lockObj != null) {
String lockValue = lockObj.toString();
if (lockValue.equals(randomStr)) {
//解除鎖
redisTemplate.delete(lockKey);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}