美文网首页
spring boot集成redis实现分布式锁

spring boot集成redis实现分布式锁

作者: 倔强的小亮 | 来源:发表于2019-07-08 10:26 被阅读0次
import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

@Component
public class RedisDistributedLock {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    /**   
     * <p>Title lock</p>   
     * <p>Description </p>   
     * @param requestId
     * @param key
     * @param expiresTime 过期时间,毫秒
     * @return   
     */  
    
    public boolean lock(String key, String requestId,  int expiresTime) {
        
        String lockScriptStr = "if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then return redis.call('pexpire',KEYS[1],ARGV[2]) else return 0 end";
        
        DefaultRedisScript<Long> longDefaultRedisScript = new DefaultRedisScript<>(lockScriptStr, Long.class);
        
        Long result = stringRedisTemplate.execute(longDefaultRedisScript, Collections.singletonList(key), requestId,String.valueOf(expiresTime));
        
        return result == 1;
        
    }

    /**   
     * <p>Title releaseLock</p>   
     * <p>Description </p>   
     * @param key
     * @param requestId
     * @return     
     */  
    
    public boolean unlock(String key, String requestId) {
        
        String unLockScriptStr = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        
        DefaultRedisScript<Long> longDefaultRedisScript = new DefaultRedisScript<>(unLockScriptStr, Long.class);
        
        Long result = stringRedisTemplate.execute(longDefaultRedisScript, Collections.singletonList(key), requestId);
        
        return result == 1;
        
    }

}

相关文章

网友评论

      本文标题:spring boot集成redis实现分布式锁

      本文链接:https://www.haomeiwen.com/subject/ymwnhctx.html