美文网首页
redis分布式锁

redis分布式锁

作者: thinking2019 | 来源:发表于2020-12-11 14:37 被阅读0次
public class RedissonDistributedLock {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedissonDistributedLock.class);

    private RedisTemplate<Serializable, Serializable> redisTemplate;

    public void setRedisTemplate(RedisTemplate<Serializable, Serializable> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public JsonResult synchronize(String lockName, LockSupplier<JsonResult> lockSupplier) {
        String key = "LOCK" + lockName;
        boolean result = tryLock(key, 1, 5000L, TimeUnit.MILLISECONDS);
        if (!result) {
            // 超时时间
            Long expire = redisTemplate.getExpire(key);

            if (expire.equals(-1L)){
//              补充过期时间
                redisTemplate.expire(key, 5000L, TimeUnit.MILLISECONDS);
            }
            LOGGER.info(key + "请勿重复操作");
            return new JsonResult(false, "请勿重复操作");
        }
        try {
            return lockSupplier.run();
        } catch (Exception e){
            LOGGER.error("锁lockName=" + lockName + "异常", e);
            throw new MyException(e.getMessage());
        }finally {
            deleteLock(key);
        }
    }

    /**
     * 创建锁
     * @param lockKey
     * @param value
     * @param releaseTime
     * @return
     */
    public boolean tryLock(String lockKey, int value, long releaseTime, TimeUnit timeUnit) {
        Boolean store = redisTemplate.opsForValue().setIfAbsent(lockKey,value);
        if(null != store && store){
            redisTemplate.expire(lockKey,releaseTime, timeUnit);
            return true;
        }
        LOGGER.error("redis加锁时,setIfAbsent返回值异常,返回值是" + store);
        return false;
    }

    /**
     * 删除锁
     * @param key
     */
    public void deleteLock(String key) {
        redisTemplate.delete(key);
    }
}

相关文章

网友评论

      本文标题:redis分布式锁

      本文链接:https://www.haomeiwen.com/subject/woujgktx.html