The content of this article is about the method of realizing high-concurrency shopping flash sales in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
We usually encounter such high concurrency problems in places such as flash sales and train ticket grabbing. I provide four solutions below:
1. Use file lock
$fp = fopen("order.lock", "r"); if(flock($fp,LOCK_EX)){ //..处理订单的代码 flock($fp,LOCK_UN); } fclose($fp);
2. Use message queue
We commonly use Memcacheq and Radis.
For example: If there are 100 tickets for users to grab, then you can put these 100 tickets in the cache and do not lock them when reading and writing. When the amount of concurrency is large, about 500 people may successfully grab tickets, so that requests after 500 can be directly transferred to the static page at the end of the event. It is impossible for 400 of the 500 people who enter to get the product. Therefore, only the first 100 people can purchase successfully according to the order in which they enter the queue. The next 400 people will go directly to the event end page. Of course, entering 500 people is just an example. You can adjust the number yourself. The activity end page must use a static page, not a database. This reduces the pressure on the database.
3. If it is a distributed cluster server, one or more queue servers are required
Xiaomi's and Taobao's rush buying are slightly different. Xiaomi's emphasis is on the moment of rush buying. Once you grab the quota, it's yours, and you can place an order and settle the payment. Taobao, on the other hand, focuses on filtering during payment. It has implemented multiple layers of filtering. For example, if it wants to sell 10 items, it will let more than 10 users grab them. It will then perform concurrent filtering during payment, reducing the number of items layer by layer in an instant. amount of concurrency.
##4, Use Memcache lock
product_lock_key is the ticket lock key
When product_key exists in memcached, all users can enter the order process.
When entering the payment process, first store add(product_lock_key, “1″) in memcached. If the return is successful, enter the payment process. If it fails, it means that someone has already entered the payment process, and the thread waits for N seconds and performs the add operation recursively.
Related recommendations:Solution to phpExcel memory overflow when exporting files
How to implement QR code in PHP Generate and identify (code)
What are the common methods for php to operate redis? Summary of methods for operating redis in PHP (with code)
The above is the detailed content of PHP method to achieve high concurrency shopping flash sale. For more information, please follow other related articles on the PHP Chinese website!