Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of high concurrency of php

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

The main content of this article is "how to solve the problem of high concurrency of php". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to solve the problem of high concurrency in php.

Sql1: query the inventory of goods

If (inventory quantity > 0) {/ / generate order... sql2: simultaneous inventory-1}

When there is no concurrency, the above process looks normal. Suppose two people place an order at the same time, and the inventory is only 1. In the sql1 phase, the inventory queried by two people is > 0, so the sql2 is finally implemented, and the inventory finally becomes-1, which is oversold. This is not the result we want.

I summed up the more popular ideas to solve this problem:

1. If you use an additional single process to process a queue, place order requests in the queue and process them one by one, there will be no concurrency problems, but the additional opening of background processes and delays will not be considered here. Here I can use message queues, we often use Memcacheq, Radis. For example, if you have 100 tickets for users to grab, you can put them in the cache without locking them when reading or writing. When the concurrency is large, about 500 people may succeed in grabbing tickets, so that for requests after 500, you can go directly to the static page at the end of the activity. It is impossible for 400 of the 500 people to get the goods. So you can buy successfully only the top 100 people according to the order in which you enter the queue. The next 400 people go directly to the end page of the event. Of course, going in for 500 people is just an example, as to how much can be adjusted by yourself. The activity end page must use a static page, not a database. This relieves the pressure on the database.

2.mysql optimistic lock, for example, the total inventory is 2, when the panic purchase event is submitted, the inventory is + 1 immediately, then the inventory is 3, then after the order is generated, check the inventory again before updating the inventory (because the order is generated as a matter of course, inventory-1, but not in a hurry, check again the inventory return result is 3) to see if it is consistent with the expected inventory quantity (here the expected inventory is 3). Roll back if there is inconsistency, indicating that the user is out of stock. When it comes to pessimistic locks here, some friends may ask, there must be optimistic locks, right? Here I would like to talk about what I know about pessimism and optimism.

Pessimistic lock and optimistic lock are two common design ideas of resource concurrent lock, and they are also a very basic concept in concurrent programming. This paper will systematically introduce the implementation of these two common locking mechanisms on database data.

Pessimistic lock (Pessimistic Lock)

The characteristic of pessimistic lock is that the lock is acquired first, and then the business operation is carried out, that is, the "pessimistic" thinks that the acquisition of lock is very likely to fail, so it is necessary to ensure that the lock is acquired successfully before business operation. The so-called "one lock, two checks and three updates" refers to the use of pessimistic locks. Generally speaking, pessimistic locks on the database need to be supported by the database itself, that is, through the commonly used select. For update operation to implement pessimistic locks. When the database executes select for update, it acquires the row lock of the data row in the select, so other concurrently executed select for update will be excluded if they try to select the same row (need to wait for the row lock to be released), thus achieving the lock effect. Row locks acquired by select for update are automatically released at the end of the current transaction, so they must be used in the transaction.

It should be noted that different databases have different implementation and support for select for update. For example, oracle supports select for update no wait, which means that if you can't get the lock, you will immediately report an error instead of waiting, mysql will not have the option of no wait. Another problem with mysql is that all scanned rows are locked during the execution of the select for update statement, which can easily cause problems. So if you use pessimistic locks in mysql, it's important to make sure that the index is gone, not a full table scan.

Optimistic lock (Optimistic Lock)

The characteristic of optimistic lock is to carry out business operation first and not to take the lock unless it is a last resort. That is, "optimistic" that most of the lock will be successful, so it is good to pick up the lock after the last step of actually updating the data after the business operation.

The implementation of optimistic lock on the database is completely logical and does not require special support from the database. The general practice is to add a version number, or timestamp, to the data that needs to be locked, and then implement it as follows:

1. SELECT data AS old_data, version AS old_version FROM... ; 2. According to the obtained data, business operations are carried out to get new_data and new_version3. UPDATE SET data = new_data, version = new_version WHERE version = old_versionif (updated row > 0) {/ / optimistic lock acquisition succeeded, operation completed} else {/ / optimistic lock acquisition failed, rollback and retry}

It doesn't matter whether the optimistic lock is in a transaction or not, the underlying mechanism is this: concurrency is not allowed when update the same row inside the database, that is, each time the database executes a update statement, it acquires the write lock of the update row, and it is not released until the row is successfully updated. Therefore, obtain the current version number of the data that needs to be locked before the business operation, and then compare the version number with the previously obtained version number again when you actually update the data, and update the version number to confirm that there are no concurrent changes between them. If the update fails, it can be considered that the old version of the data has been concurrently modified and no longer exists. If the lock acquisition failed, the entire business operation needs to be rolled back and the whole process can be retried as needed. All right, here's a nagging summary of these two locks:

Summary

Optimistic lock is less expensive than pessimistic lock when there is no lock failure, but the rollback cost is higher in the event of failure, so it is suitable for scenarios with low probability of lock failure and can improve system concurrency performance.

Optimistic locks are also suitable for some special scenarios, such as where pessimistic locks are not applicable, such as not being able to keep a connection with the database during business operations.

3. According to the update result, we can add a judgment condition update table set inventory = xxx where inventory > 0 in sql2. If false is returned, it indicates that the inventory is insufficient and rolls back the transaction.

4. With the help of file exclusive lock, when processing a request to place an order, lock a file with flock. If the lock fails to indicate that another order is being processed, either wait or directly prompt the user that the server is busy.

The approximate code is as follows:

Blocking (waiting) mode

Non-blocking mode

5. If it is a distributed cluster server, you need one or more queue servers to buy Xiaomi and Taobao, which are slightly different. Xiaomi focuses on the moment it grabs the quota, which is yours, and you can issue an order settlement. While Taobao focuses on filtering at the time of payment, doing multi-layer filtering, such as selling 10 items, it will let more than 10 users grab it, and then carry out concurrent filtering at the time of payment, layer by layer to reduce the amount of concurrency in an instant.

6. Use redis lock product_lock_key as ticket lock key when product_key exists in redis, all users can enter the order placing process. When entering the payment process, first store sadd (product_lock_key, "1") in redis. If the return is successful, enter the payment process. If not, someone has entered the payment process, then the thread waits for N seconds and recursively executes the sadd operation.

At this point, I believe you have a deeper understanding of "how to solve the problem of high concurrency in php". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report