Redis redisTemplate.execute 执行锁

 Redis 脚本执行redis锁代码如下:

    /**
     * 加锁
     */
    public final static String SCRIPT_LOCK = "local key = KEYS[1];\n"
            + "local value = ARGV[1];\n"
            + "local ttlMillis = tonumber(ARGV[2]);\n"
            + "if ( redis.call('SETNX', key, value) == 1 ) then\n"
            + "    redis.call('PEXPIRE', key, ttlMillis);\n"
            + "    return true;\n"
            + "end;";


public boolean tryLock(String key, String val, Long timeMillis) {
        return tryLock(RedisConstants.KEY + key,SCRIPT_LOCK, val, timeMillis,
                TimeUnit.MILLISECONDS);
    }

    public boolean tryLock(String key, String scriptText, String val, Long timeout, TimeUnit unit) {
        DefaultRedisScript script = new DefaultRedisScript<>();
        script.setScriptText(scriptText);
        script.setResultType(Boolean.class);
        long rawTimeout = TimeoutUtils.toMillis(timeout, unit);
        return redisTemplate.execute(script, Collections.singletonList(key), val, rawTimeout);
    }
@Configuration
public class RedisTemplateAutoConfiguration {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory rcf) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(rcf);

        //使用StringRedisSerializer对Key序列号,使用Jackson对Value序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

你可能感兴趣的:(Redis,redis,java,数据库)