


PHP high concurrency testing: Case study on preventing inventory oversold
In the previous article "How to prevent product inventory oversold under high concurrency in PHP", we talked about related issues about preventing oversold product inventory under high concurrency. Let's do it together. Let’s take a look at the related content of concurrency testing to prevent inventory oversold. I hope it will be helpful to everyone.
This article is based on the test case of "How to prevent product inventory from being oversold under high concurrency in PHP". Recommended study: "PHP Learning Tutorial"
1. Ordinary order
During concurrent testing, product table id =1 name = Daohuaxiang Rice store = 15
请求总数30 每次10个并发 ab -n 30 -c 10 http://xxxxx.top/code/the_limit/add_order.php
Result:
There were 15 successful inventory reductions, and the store inventory had a negative number of -7. 8 times it was judged that the inventory was insufficient (negative inventory numbers are incorrect and not allowed)
2. Unsigned mode
Adjust back to product table id =1 name = Daohuaxiang Rice store = 15
请求总数30 每次10个并发 ab -n 30 -c 10 http://xxxxx.top/code/the_limit/unsigned.php
Result:
There have been 15 successful inventory reductions and the store inventory has a negative number of -6. 9 times it was judged that the inventory was insufficient (negative inventory numbers are incorrect and not allowed)
Only adding for update to the query statement has little effect in locking
3. Mysql transaction, lock operation row
Adjust back to product table id =1 name = Daohuaxiang Rice store = 15
请求总数30 每次10个并发 ab -n 30 -c 10 http://xxxxx.top/code/the_limit/ACID.php
Result:
There were 15 successful inventory reductions. The store did not have a negative inventory. 15 times it was judged that the inventory was insufficient (negative inventory numbers are incorrect and not allowed)
The effect of adding transactions is good ab -n 3000 -c 1000 concurrency can also be tolerated
4. Non-blocking file exclusive lock
Blocking form
Non-blocking Form
The effect does not appear negative, but in terms of performance: Transaction>Blocking>Non-blocking
5. Redis Queue
The code is slightly different from the previous one There are adjustments to the optimistic lock version
<?php $redis =new Redis(); $redis->connect("127.0.0.1", 6379); $redis->auth('PASSWORD'); $redis->watch('sales');//乐观锁 监视作用 set() 初始值0 $sales = $redis->get('sales'); //var_dump($sales); exit; db(); global $con; // 查询商品信息 //$product_id = 1; //$sql = "select * from products where id={$product_id}"; //$result = mysqli_query($con, $sql); //$row = mysqli_fetch_assoc($result); //$store = $row['store']; // 库存 $n = 15; if ($sales >= $n) { insertLog('库存为0 秒杀失败'); exit('秒杀结束'); } //redis开启事务 $redis->multi(); $redis->incr('sales'); //将 key 中储存的数字值增一 ,如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。 $res = $redis->exec(); //成功1 失败0 if ($res) { //秒杀成功 $con = new mysqli('localhost','root','PASSWORD','dev'); if (!$con) { echo "数据库连接失败"; } $product_id = 1;// 商品ID $buy_num = 1;// 购买数量 sleep(1); $sql = "update products set store=store-{$buy_num} where id={$product_id}"; if (mysqli_query($con, $sql)) { echo "秒杀完成"; insertLog('恭喜 秒杀成功'); } } else { insertLog('抱歉 秒杀失败'); exit('抢购失败'); } function db() { global $con; $con = new mysqli('localhost','root','WOrd1234.*','dev'); if (!$con) { echo "数据库连接失败"; } } /** * 记录日志 */ function insertLog($content) { global $con; $sql = "INSERT INTO `order_log` (content) values('$content')"; mysqli_query($con, $sql); }
ab -n 30 -c 10 http://xxxxxx.top/code/the_limit/optimistic\ _redis_lock.php
Final conclusion Concurrency challenges give priority to redis with good performance
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of PHP high concurrency testing: Case study on preventing inventory oversold. For more information, please follow other related articles on the PHP Chinese website!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools
