通过 RedisTemplate 和 Redis 实现锁的功能

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);
    }
上一篇:jedis以及SpringBoot集成redis


下一篇:Markdown学习