Demo of distributed lock based on redis (circular retry) (better than recursive retry)

forever HelloWorld 2022-09-23 09:20:28 阅读数:301

 @Autowiredprivate StockMapper stockMapper;/*** redisTemplate*///StringRedisTemplate and RedisTemplate serializers are [email protected] StringRedisTemplate redisTemplate;//The optimistic lock of redis ensures thread safety, but the efficiency is relatively slow, and the connection is not enough due to the performance problem of the machine, so it is not recommended to use the optimistic lock of redispublic void deduct() {//lock setnxBoolean lockFirst = this.redisTemplate.opsForValue().setIfAbsent("lock", "111");//while(!lockFirst){try {Thread.sleep(50);} catch (InterruptedException e) {throw new RuntimeException(e);}}try {// 1. Query inventory informationString stock = redisTemplate.opsForValue().get("stock").toString();//2. Determine whether the inventory is sufficientif (stock != null && stock.length() != 0) {Integer st = Integer.valueOf(stock);if (st > 0) {// deduct inventoryredisTemplate.opsForValue().set("stock", String.valueOf(--st));}}} finally {//unlockthis.redisTemplate.delete("lock");}}
版权声明:本文为[forever HelloWorld]所创,转载请带上原文链接,感谢。