Redis教程

通过 RedisTemplate 和 Redis 实现锁的功能

本文主要是介绍通过 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);
    }
这篇关于通过 RedisTemplate 和 Redis 实现锁的功能的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!