数据库
首页 > 数据库> > 基于Redis setNX命令实现分布式加解锁

基于Redis setNX命令实现分布式加解锁

作者:互联网

1、setNX命令说明:
SET resource_name my_random_value NX PX 30000
2、代码演示:
@Service
public class BaseSetNXDistributeLockService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseSetNXDistributeLockService.class);

    @Autowired
    private RedisTemplate redisTemplate;

    public String redisLock() {
        LOGGER.info("我进入了方法!");
        String key = "redisKey";
        String value = UUID.randomUUID().toString();

        RedisCallback<Boolean> redisCallback = connection -> {
            //设置NX
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
            //设置过期时间
            Expiration expiration = Expiration.seconds(30);
            //序列化key
            byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
            //序列化value
            byte[] redisValue = redisTemplate.getValueSerializer().serialize(value);
            //执行setnx操作
            Boolean result = connection.set(redisKey, redisValue, expiration, setOption);
            return result;
        };
        //获取分布式锁
        Boolean lock = (Boolean) redisTemplate.execute(redisCallback);
        if (lock) {
            LOGGER.info("我进入了锁!");
            try {
                Thread.sleep(15000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n"+
                        "  return redis.call(\"del\",KEYS[1])\n"+
                        "else\n"+
                        "  return 0\n"+
                        "end";
                RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);
                List<String> keys = Arrays.asList(key);
                Boolean result = (Boolean) redisTemplate.execute(redisScript,keys,value);
                LOGGER.info("释放锁的结果:"+result);

                
            }
        }
        return "方法执行完成!";
    }

}

标签:return,String,解锁,Redis,value,Boolean,result,setNX,redisTemplate
来源: https://blog.csdn.net/weixin_40857858/article/details/120713706