search
HomeBackend DevelopmentPHP TutorialDetailed explanation of examples of rush buying solutions under large traffic using PHP

This article mainly introduces a brief discussion of PHP's plan to realize rush buying under large traffic. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look, I hope it can help everyone.

It is required to display a real-time countdown of hours, minutes and seconds. Modifying the date and time on the client side will not affect the normal display of the countdown (that is, based on the server time).

In fact, this has the same requirements as the time limit function of many examination and other systems.

You can’t use ajax to get the server time every second, so the real-time countdown must be implemented with javascript. This is very simple, there are a lot of examples on the Internet.

The current problem is to solve the impact of the user-side modified date and time on our display.

The solution is to calculate the time difference between the client time and the server time, so that the problem is solved.

In this way, you only need to run php once, and the real-time countdown time will be synchronized with the server time.

The theory is synchronization, but the actual test will have an error of 1 second. (The specific reason is related to the Internet speed. The faster the Internet speed, the smaller the error.) But this will never affect our above requirements.

Note: The flash sale time is from 1:00 am to 10:00 pm.

Code is as follows:


<?php
//php的时间是以秒算。js的时间以毫秒算
date_default_timezone_set(&#39;PRC&#39;); 
//date_default_timezone_set("Asia/Hong_Kong");//地区
//配置每天的活动时间段 
$starttimestr = "08:00:00"; 
$endtimestr = "22:00:00";
$starttime = strtotime($starttimestr); 
$endtime = strtotime($endtimestr); 
$nowtime = time(); 
if ($nowtime<$starttime){ 
die("活动还没开始,活动时间是:{$starttimestr}至{$endtimestr}"); 
} 
$lefttime = $endtime-$nowtime; //实际剩下的时间(秒) 
?>
<script language="JavaScript"> 
</script>
<h4 id="strong-nbsp-id-RemainH-XX-strong-strong-nbsp-id-RemainM-XX-strong-strong-nbsp-id-RemainS-XX-strong"><strong id="RemainH">XX</strong>:<strong id="RemainM">XX</strong>:<strong id="RemainS">XX</strong></h4>

There seems to be no problem with the above, but when encountering traffic, there will be some problems with the wrong quantity, such as caused by the concurrent entry of large traffic into the database. The problem of negative inventory

We know that the database processes SQL one by one. Assume that the process of purchasing goods is like this:

sql1: Query product inventory


if(库存数量 > 0) 
{ 
//生成订单… 
sql2:库存-1 
}

When there is no concurrency, the above process looks so perfect. Assume that two people place orders at the same time, and there is only 1 inventory. In the sql1 stage, the inventory queried by both people is >0 , so sql2 was finally executed, and the inventory finally became -1, indicating that it was oversold. Either replenish the inventory or wait for user complaints.

The more popular ideas to solve this problem:

1. Use an additional single process to process a queue, put the order requests in the queue, and process them one by one, so there will be no concurrency problems Yes, but the additional background processes and latency issues will not be considered.

2. Database optimistic locking, which roughly means querying the inventory first, then immediately adding 1 to the inventory, and then after the order is generated, query the inventory again before updating the inventory to see if it is consistent with the expected inventory quantity. If it is consistent, it will be rolled back if it is inconsistent, and the user will be prompted that the inventory is insufficient.

3. To judge based on the update result, we can add a judgment condition update in sql2... where inventory > 0. If false is returned, it means that the inventory is insufficient and the transaction will be rolled back.

4. With the help of file exclusive lock, when processing the order request, use flock to lock a file. If the lock fails, it means that other orders are being processed. At this time, either wait or directly prompt the user "server busy"

This article is going to talk about the fourth solution. The approximate code is as follows:

Blocking (waiting) mode


<?php
$fp = fopen("lock.txt", "w+");
if(flock($fp,LOCK_EX))
{
 //..处理订单
 flock($fp,LOCK_UN);
}
fclose($fp);
?>

Non-blocking mode


##

<?php
$fp = fopen("lock.txt", "w+");
if(flock($fp,LOCK_EX | LOCK_NB))
{
 //..处理订单
 flock($fp,LOCK_UN);
}
else
{
 echo "系统繁忙,请稍后再试";
}
fclose($fp);
?>

Related recommendations:


How does PHP solve the problem of large traffic and high website traffic? Concurrency

#PHP Large traffic optimization?

PHP product flash sale timing implementation (solution to large traffic)

The above is the detailed content of Detailed explanation of examples of rush buying solutions under large traffic using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.