Implementation of optimistic locking in redis (code)

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

implementationoptimisticlockingrediscode
/****///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 {operations.watch((K) "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]所创,转载请带上原文链接,感谢。 https://javamana.com/2022/266/202209230914232131.html
免责声明&版权声明:本站所有内容均来自网络/签约作者创作。网站没有任何收费内容,皆在打造垂直领域的免费知识聚合。本站内容仅代表作者观点,与本站立场无关,本站不对其真实合法性负责。
如有内容侵犯了您的权益/作者内容违反法律法规,请告知,本站将及时删除/封禁作者账号。联系网站管理员,我们将在24工作时内处理。
Copyright © 2020 All Rights Reserved.