Implementation of optimistic locking in redis (code)

The HelloWorld forever 2022-09-23 09:20:17 阅读数:984

/****///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() {//Optimistic lock of redis, monitoring inventory information// watchthis.redisTemplate.execute(new SessionCallback() {@[email protected]  Object execute(RedisOperations operations) throws DataAccessException { "stock");//1. Query inventory informationString stock = operations.opsForValue().get("stock").toString();//2. Determine whether the inventory is sufficientif (stock != null && stock.length() != 0) {Integer st = Integer.valueOf(stock);System.out.println("The quantity of inventory is: "+st);if (st > 0) {// start transactionoperations.multi();//3. Deduct inventoryoperations.opsForValue().set((K) "stock", (V) String.valueOf(--st));//exec execute the operationList exec = operations.exec();// perform the operation, retryif(exec == null || exec.size() == 0){//Recursive call may lead to stack overflow, according to the performance of the computer, you can consider taking a breakThread.sleep(40);deduct();}return exec;}}return null;}});}
版权声明:本文为[The HelloWorld forever]所创,转载请带上原文链接,感谢。
Copyright © 2020 All Rights Reserved.