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

2021/10/12 2:14:28

本文主要是介绍基于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 "方法执行完成!";
    }

}


这篇关于基于Redis setNX命令实现分布式加解锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程