Case Analysis of distributed Lock implemented by redis
0 & & goods_stock > = goodsQuantity) {/ / 1. Query the database object Goods goods = goodsMapper.findGoodsById (goodsId); / / 2. Update the inventory quantity in the database goods.setGoods_stock (goods.getGoods_stock ()-goodsQuantity); goodsMapper.updateGoodsStock (goods); / / 3. Synchronize redisTemplate.boundHashOps ("goods_info") .put (goods.getGoods_id (), goods.getGoods_stock ()) in Redis; log.info ("Commodity Id: {}, remaining inventory in Redis: {}", goodsId, goods.getGoods_stock ()); / / release lock lock.releaseLock (LOCK_NAME, identifier); return 1 } else {log.info ("Commodity Id: {}, insufficient inventory! , inventory: {}, purchase quantity: {} ", goodsId, goods_stock, goodsQuantity); / / release lock lock.releaseLock (LOCK_NAME, identifier); return-1;}
Controller layer
Import com.springlock.service.SkillService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Scope;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@Scope ("prototype") / / prototype multiple instances, singleton single instance public class SkillController {@ Autowired SkillService skillService; @ RequestMapping ("/ skill") public String skill () {Integer count = skillService.seckill ("1", 1L) Return count > 0? "order issued successfully" + count: "order issued failed" + count;}} 4, distributed lock test
Start the SpringBoot project on two servers with ports 8888 and 9999, respectively. After starting port 8888, modify the profile port to 9999 and start another application
Then use jmeter for concurrent testing, open two thread groups, place orders on behalf of two servers, 20 threads per second, 25 cycles, a total of 1000 orders.
View the console output:
Note: when the concurrency of the lock is too high, there will be a part of the failure rate. Programs written manually will have concurrency problems because of the non-atomic nature of the operation. The implementation of the lock is only to demonstrate the principle and is not suitable for production.
Jmeter aggregation report
After reading this, the article "instance Analysis of redis distributed Lock implementation" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.