通过 RedisTemplate 和 Redis 实现锁的功能

FLowUs邀请链接:https://flowus.cn/login?code=AXNU63
FlowUs邀请码:AXNU63


private static final Long EXEC_RESULT = 1L;

    private static DefaultRedisScript<Long> redisScript = new DefaultRedisScript<Long>();

    private static RedisSerializer<String> argsSerializer = new StringRedisSerializer();

    private static RedisSerializer resultSerializer = new StringRedisSerializer();

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean getDistributedLock(String key, String requestId, String expireTime) {
        String script =
            "if redis.call('setNx',KEYS[1],ARGV[1]) then " +
            "    if redis.call('get',KEYS[1])==ARGV[1] then " +
            "        return redis.call('expire',KEYS[1],ARGV[2]) " +
            "    else " +
            "        return 0 " +
            "    end " +
            "end";
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        Long result = redisTemplate.execute(redisScript, argsSerializer, resultSerializer, Collections.singletonList(key), requestId, expireTime);
        System.out.println("获取锁:" + result);
        return EXEC_RESULT.equals(result);
    }

    @Override
    public boolean releaseDistributedLock(String key, String requestId) {
        String script =
            "if redis.call('get',KEYS[1]) == ARGV[1] then " +
            "    return redis.call('del',KEYS[1]) " +
            "else " +
            "    return 0 " +
            "end";
        redisScript.setScriptText(script);
        redisScript.setResultType(Long.class);
        Long result = redisTemplate.execute(redisScript, argsSerializer, resultSerializer, Collections.singletonList(key), requestId);
        System.out.println("释放锁:" + result);
        return EXEC_RESULT.equals(result);
    }
posted @ 2021-08-12 02:18  wbytts  阅读(411)  评论(0编辑  收藏  举报