当前位置:网站首页>Example code of second kill based on MySQL optimistic lock
Example code of second kill based on MySQL optimistic lock
2022-07-01 13:03:00 【1024 questions】
explain
Concrete realization
Code implementation
explainIf your project traffic is very small , Don't worry about concurrent purchase requests at all , So it doesn't make much sense to do such a system . But if your system is like 12306 like that , Accept the test of high concurrent visits and orders , Then you need a complete set of process protection measures , To ensure that your system will not be hung up during peak user traffic .
Advanced redis+mq Realization : Reference resources springboot + rabbitmq + redis Achieve second kill
Concrete realizationStrictly prevent oversold
Ensure the user experience : High and low , Don't open the web page , Payment failed , The shopping cart can't get in , The address can't be changed
Prevent black production : Prevent malicious people from pocketing all the benefits you should have distributed to the masses through various technical means
1、 The core
mysql Optimistic lock prevents oversold
Optimistic lock refers to the operation of the database ( update operation ), The idea is optimistic , Think this operation will not lead to conflict , When operating data , Without any other special treatment ( That is, no lock ), And after the update , To judge whether there is a conflict .
Here is the reference. Usually, the implementation is like this : When the data in the table is operated ( to update ), First, add a version to the data table (version) Field , Every time you operate , Add the version number of that record to 1. That is to find out the record first , Take out version Field , If you want to operate on that record ( to update ), Then judge the moment first version Whether the value of is the same as the value of version The values are equal , If equal , It means that during this period , There is no other program to operate it , Then you can perform the update , take version Add... To the value of the field 1; If you find out when you update version Value and just get out of version The values of , It means that there are other procedures to operate it during this period , Do not update .
2、 Create table statement
stock Commodity list
-- ------------------------------ Table structure for stock-- ----------------------------DROP TABLE IF EXISTS `stock`;CREATE TABLE `stock` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL DEFAULT '' COMMENT ' name ', `count` int(11) NOT NULL COMMENT ' stock ', `sale` int(11) NOT NULL COMMENT ' sold ', `version` int(11) NOT NULL COMMENT ' Optimism lock , Version number ', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;Initialization data :

stock_order The order sheet
-- ------------------------------ Table structure for stock_order-- ----------------------------DROP TABLE IF EXISTS `stock_order`;CREATE TABLE `stock_order` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `sid` int(11) NOT NULL COMMENT ' stock ID', `name` varchar(30) NOT NULL DEFAULT '' COMMENT ' Name of commodity ', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ' Creation time ', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;3、 The business process

1、pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--mysql--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency>2、model

It can be configured through reverse engineering , Reference resources idea+mybatis Reverse engineering
4、dao
public interface StockMapper { Stock checkStock(Integer id);// Verify inventory int updateSale(Stock stock);// Deducting inventory }public interface StockOrderMapper { // Create order void createOrder(StockOrder order);}5、sql
Commodity verification and inventory reduction
<select id="checkStock" parameterType="java.lang.Integer" resultType="com.yy.msserver.model.vo.Stock"> select * from stock where id = #{id} </select> <update id="updateSale" parameterType="com.yy.msserver.model.vo.Stock" > update stock set sale = #{sale,jdbcType=INTEGER} + 1, version = #{version,jdbcType=INTEGER} + 1, count = #{count,jdbcType=INTEGER} - 1 where id = #{id,jdbcType=INTEGER} AND count > 0 AND version = #{version} </update>Place the order
<insert id="createOrder" parameterType="com.yy.msserver.model.vo.StockOrder"> insert into stock_order (sid, name, create_time) values (#{sid,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}) </insert>6、service
public interface StockOrderService { public Integer createOrder(Integer id);}7、 Realization
/** * @author code * @Date 2022/6/24 9:25 * Description Order fulfillment * Version 1.0 */@Servicepublic class StockOrderServiceImpl implements StockOrderService { @Autowired private StockOrderMapper stockOrderMapper; @Autowired private StockMapper stockMapper; @Override @Transactional(rollbackFor = Exception.class) public Integer createOrder(Integer id) { // Verify inventory Stock stock = checkStock(id); if(stock.getCount()>0){ System.out.println(" Current stock :" + stock.getCount()); // Inventory deduction if(updateSale(stock) == 1){ return createOrder(stock); }else { return 0; } } return 0; } // Verify inventory private Stock checkStock(Integer id) { return stockMapper.checkStock(id); } // Inventory deduction private int updateSale(Stock stock){ return stockMapper.updateSale(stock); } // Place the order private Integer createOrder(Stock stock){ StockOrder order = new StockOrder(); order.setSid(stock.getId()); order.setCreateTime(new Date()); order.setName(stock.getName()); stockOrderMapper.createOrder(order); return order.getId(); }}8、 test
simulation 100 Participation and activities
@SpringBootTestclass MsServerApplicationTests { @Autowired private StockOrderService stockOrderService; @Test void contextLoads() throws InterruptedException { // Inventory initialization is 10, Through here CountDownLatch And thread pool emulation 100 concurrent int threadTotal = 100; ExecutorService executorService = Executors.newCachedThreadPool(); final CountDownLatch countDownLatch = new CountDownLatch(threadTotal); for (int i = 0; i < threadTotal ; i++) { int uid = i; executorService.execute(() -> { try { stockOrderService.createOrder(1); } catch (Exception e) { e.printStackTrace(); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); }}9、 result

Commodity list

The order sheet

This article is based on mysql This is the article about the example code of optimistic lock to realize seckill , More about mysql Please search the previous articles of software development network or continue to browse the relevant articles below. I hope you will support software development network more in the future !
边栏推荐
- 题目 2612: 蓝桥杯2021年第十二届省赛真题-最少砝码(枚举找规律+递推)
- Development trend and market demand analysis report of China's high purity copper industry Ⓕ 2022 ~ 2028
- Localtime can't re-enter. It's a pit
- VM virtual machine configuration dynamic IP and static IP access
- 简单的两个圆球loading加载
- be based on. NETCORE development blog project starblog - (13) add friendship link function
- Project deployment is not difficult at all!
- 路由基础之OSPF LSA详细讲解
- 软件测试中功能测试流程
- MySQL报错1040Too many connections的原因以及解决方案
猜你喜欢

ZABBIX 6.0 source code installation and ha configuration

leetcode:329. 矩阵中的最长递增路径【dfs + cache + 无需回溯 + 优雅】
![[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world](/img/41/76687ea13e1722654b235f2cfa66ce.png)
[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world

软件测试中功能测试流程

Introduction to reverse debugging PE structure input table output table 05/07

Feign & Eureka & zuul & hystrix process

图灵奖得主Judea Pearl:最近值得一读的19篇因果推断论文

VM虚拟机配置动态ip和静态ip访问

简单的两个圆球loading加载

基于.NetCore开发博客项目 StarBlog - (13) 加入友情链接功能
随机推荐
Topic 1004: the story of cows (recursion)
Zabbix 6.0 源码安装以及 HA 配置
Feign & Eureka & Zuul & Hystrix 流程
leetcode:241. Design priority for operation expression [DFS + Eval]
Fundamentals of number theory and its code implementation
Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing
简单的两个圆球loading加载
MySQL statistical bill information (Part 2): data import and query
【大型电商项目开发】性能压测-压力测试基本概念&JMeter-38
codeforces -- 4B. Before an Exam
The difference between memcpy and strcpy
Vs code setting Click to open a new file window without overwriting the previous window
Tencent security released the white paper on BOT Management | interpreting BOT attacks and exploring ways to protect
PG basics -- Logical Structure Management (trigger)
MySQL gap lock
How can genetic testing help patients fight disease?
Report on the "14th five year plan" and investment strategy recommendations for China's industrial robot industry 2022 ~ 2028
CV顶会最佳论文得主分享:好论文是怎么炼成的?
R语言基于h2o包构建二分类模型:使用h2o.gbm构建梯度提升机模型GBM、使用h2o.auc计算模型的AUC值
[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world