spring boot集成redis实现分布式锁

2019-07-08  本文已影响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;
        
    }

}
上一篇 下一篇

猜你喜欢

热点阅读