search
HomeBackend DevelopmentPHP TutorialPHP 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.

PHP high concurrency testing: Case study on preventing inventory oversold

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(&#39;PASSWORD&#39;);
$redis->watch(&#39;sales&#39;);//乐观锁 监视作用 set()  初始值0
$sales = $redis->get(&#39;sales&#39;);
//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[&#39;store&#39;];
// 库存
$n = 15;
if ($sales >= $n) {
    insertLog(&#39;库存为0 秒杀失败&#39;);
    exit(&#39;秒杀结束&#39;);
}

//redis开启事务
$redis->multi();
$redis->incr(&#39;sales&#39;); //将 key 中储存的数字值增一 ,如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。
$res = $redis->exec(); //成功1 失败0

if ($res) {
    //秒杀成功
    $con = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;PASSWORD&#39;,&#39;dev&#39;);
    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(&#39;恭喜 秒杀成功&#39;);
    }

} else {
    insertLog(&#39;抱歉 秒杀失败&#39;);
    exit(&#39;抢购失败&#39;);
}

function db()
{
    global $con;
    $con = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;WOrd1234.*&#39;,&#39;dev&#39;);
    if (!$con) {
        echo "数据库连接失败";
    }
}

/**
 * 记录日志
 */
function insertLog($content)
{
    global $con;
    $sql = "INSERT INTO `order_log` (content) values(&#39;$content&#39;)";
    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!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

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

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

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

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

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.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

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

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

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

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

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.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

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

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SecLists

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

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

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

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools