Implementation of optimistic locking in redis (code)

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

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;}});}
copyright:author[The HelloWorld forever],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/266/202209230914232131.html
disclaimer©right: All content on this site is created by signed authors. The site does not charge for any content, but is building free knowledge aggregations in vertical areas. The content of this site only represents the views of the author, has nothing to do with the position of this site, this site is not responsible for its true legality.
If any content violates your rights and interests/the author's content violates laws and regulations, please inform us and we will delete/ban the author's account in time. contactWebmaster,We will deal with it within 24 working hours.
Copyright © 2020 All Rights Reserved.