当前位置:网站首页>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 !
边栏推荐
- 阿霍的三个阶段
- C language learning
- Report on the "14th five year plan" and investment strategy recommendations for China's industrial robot industry 2022 ~ 2028
- MySQL gap lock
- Powerful, easy-to-use, professional editor / notebook software suitable for programmers / software developers, comprehensive evaluation and comprehensive recommendation
- Mobile note application
- Flinkcdc should extract Oracle in real time. What should be configured for oracle?
- MHA high availability cluster deployment and failover of database
- 路由基础之OSPF LSA详细讲解
- 腾讯总考epoll, 很烦
猜你喜欢

不同的测试技术区分

软件测试中功能测试流程

Vs code set code auto save

MHA high availability cluster deployment and failover of database

Jenkins+webhooks-多分支参数化构建-

MySQL statistical bill information (Part 2): data import and query

codeforces -- 4B. Before an Exam

基因检测,如何帮助患者对抗疾病?

【邂逅Django】——(二)数据库配置
![[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
随机推荐
Topic 2612: the real topic of the 12th provincial competition of the Blue Bridge Cup in 2021 - the least weight (enumerating and finding rules + recursion)
Tencent Li Wei: deeply cultivate "regulatory technology" to escort the steady and long-term development of the digital economy
ROS2 Foxy depthai_ros教程
我花上万学带货:3天赚3元,成交靠刷单
买卖其实也有风险
请问flink mysql cdc 全量读取mysql某个表数据,对原始的mysql数据库有影响吗
The future of game guild in decentralized games
Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing
[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world
基于.NetCore开发博客项目 StarBlog - (13) 加入友情链接功能
79. Word search [DFS + backtracking visit + traversal starting point]
SQLAlchemy在删除有外键约束的记录时,外键约束未起作用,何解?
logstash报错:Cannot reload pipeline, because the existing pipeline is not reloadable
香港科技大学李泽湘教授:我错了,为什么工程意识比上最好的大学都重要?
数论基础及其代码实现
I spent tens of thousands of dollars to learn and bring goods: I earned 3 yuan in three days, and the transaction depends on the bill
高薪程序员&面试题精讲系列118之Session共享有哪些方案?
天青色等烟雨
快速整明白Redis中的压缩列表到底是个啥
Nc100 converts strings to integers (ATOI)