Redis實現鎖機制

使用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();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章