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();
    }
}
发布了331 篇原创文章 · 获赞 581 · 访问量 265万+

猜你喜欢

转载自blog.csdn.net/vtopqx/article/details/104827048
今日推荐