当前位置:网站首页>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 !
边栏推荐
- 使用nvm管理nodejs(把高版本降级为低版本)
- Redis exploration: cache breakdown, cache avalanche, cache penetration
- 有没有大佬 遇到过flink监控postgresql数据库, 检查点无法使用的问题
- 网络socket的状态要怎么统计?
- 请问flink mysql cdc 全量读取mysql某个表数据,对原始的mysql数据库有影响吗
- 软件测试中功能测试流程
- Asp.netcore利用dynamic简化数据库访问
- Redis explores cache consistency
- 简单的两个圆球loading加载
- 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
猜你喜欢

The popular major I chose became "Tiankeng" four years later

Hardware development notes (9): basic process of hardware development, making a USB to RS232 module (8): create asm1117-3.3v package library and associate principle graphic devices

ZABBIX 6.0 source code installation and ha configuration

Different test techniques

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

软件测试中功能测试流程

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

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

Fiori applications are shared through the enhancement of adaptation project
![Idea of [developing killer]](/img/74/f4a18afd2b86373996e4ca62b50f88.png)
Idea of [developing killer]
随机推荐
Svg diamond style code
工具箱之 IKVM.NET 项目新进展
【开发大杀器】之Idea
Ustime wrote a bug
Tencent Li Wei: deeply cultivate "regulatory technology" to escort the steady and long-term development of the digital economy
Logstash error: cannot reload pipeline, because the existing pipeline is not reloadable
During Oracle CDC data transmission, the CLOB type field will lose its value during update. There is a value before update, but
Project deployment is not difficult at all!
哪个券商公司开户佣金低又安全又可靠
腾讯总考epoll, 很烦
Feign & Eureka & zuul & hystrix process
Scene function of wooden frame
Eurake partition understanding
Zero copy technology of MySQL
【历史上的今天】7 月 1 日:分时系统之父诞生;支付宝推出条码支付;世界上第一支电视广告
下半年还有很多事要做
Has anyone ever encountered this situation? When Oracle logminer is synchronized, the value of CLOB field is lost
[encounter Django] - (II) database configuration
数字化转型再下一城,数字孪生厂商优锘科技宣布完成超3亿元融资
CV顶会最佳论文得主分享:好论文是怎么炼成的?