分布式锁-redis

Posted wanhua.wu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分布式锁-redis相关的知识,希望对你有一定的参考价值。

 

@Autowired
    private RedisTemplate<String, Object> redisTemplate;


/**
     * 获取分布式锁 - 过期时间
     * @param key
     * @param expireTime 毫秒
     * @return
     */
    public Object getExpiredLock(String key, Long expireTime) {
        Long value = System.currentTimeMillis() + expireTime;
        return redisTemplate.execute((RedisCallback) connection -> {
            int count = 3;
            while (count > 0) {
                try {
                    JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                    return commands.set(key, String.valueOf(value), "NX", "PX", expireTime);
                } catch (Exception e) {
                    logger.error("getExpiredLock exception key={}, count={}:", key, count, e);
                    count--;
                }
            }
            return null;
        });
    }


/**
     * 获取分布式锁 - 过期时间,value
     * @param key
     * @param expireTime
     * @return
     */
    public Object getExpiredLock(String key, Long expireTime, String value) {
        return redisTemplate.execute((RedisCallback) connection -> {
            int count = 3;
            while (count > 0) {
                try {
                    JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                    return commands.set(key, value, "NX", "PX", expireTime);
                } catch (Exception e) {
                    logger.error("getExpiredLock exception key={}, count={}:", key, count, e);
                    count--;
                }
            }
            return null;
        });
    }

/**
     * 获取分布式锁value
     * @param key
     * @return
     */
    public Object getValue4ExpiredLock(String key) {
        return redisTemplate.execute((RedisCallback) connection -> {
            int count = 3;
            while (count > 0) {
                try {
                    JedisCommands commands = (JedisCommands) connection.getNativeConnection();
                    return commands.get(key);
                } catch (Exception e) {
                    logger.error("getExpiredLock exception key={}, count={}:", key, count, e);
                    count--;
                }
            }
            return null;
        });
    }


/**
     * 删除任务队列锁
     * @param lockKey
     */
    public void deleteLock(String lockKey) {
        int count = 3;
        while (count > 0) {
            try {
                if (redisTemplate.hasKey(lockKey) && Long.valueOf(""+getValue4ExpiredLock(lockKey)) > System.currentTimeMillis()) {
                    // 当前时间比该锁对应的value小,说明未过期,并占有该锁,可以直接删除
                    redisTemplate.delete(lockKey);
                    logger.info("删除list锁:{}", lockKey);
                } else {
                    logger.info("任务锁已过期, taskListLockKey={}", lockKey);
                }
                break;
            } catch (Exception e) {
                logger.error("deleteLock count={}", count, e);
                count--;
            }
        }

    }

  

        // 获取分布式锁
        if (redisService.getExpiredLock(key, 5000L) == null) {
            return;
        }    


        // 删除分布式锁
         redisService.deleteLock(key);    

  

 

以上是关于分布式锁-redis的主要内容,如果未能解决你的问题,请参考以下文章

分布式锁三种解决方案

分布式锁Redis分布式锁注解灵活实现

分布式Redis锁并发编程Redis分布式锁实例

Redis进阶学习03---Redis完成秒杀和Redis分布式锁的应用

间谍高度(上帝视角)和redis分布式锁

分布式锁,及Redis实现分布式锁