This article describes the method of php to prevent blocking requests based on session lock. Share it for your reference, as follows:
illustrate:
This is a reference website/php5/how-to-prevent-blocking-php-requests/Translation of , the previous articleSession blocking problem and solution in PHP programmingA simple analysis of the solution to php session blocking, and another solution is given here.
text:
The number of concurrent connections that modern browsers limit to a host is generally 4 or 6. This means that if your web page loads dozens of assert files (js, images, css) from the same host, a queue will occur due to the concurrency limit. Also even worse, this problem also occurs in php scripts that use session.
question:
The default file storage of php session is used. When requesting a php file that requires the session operation (session_start()
) When this file will be locked by the first process operating session, causing other requests to block. Other requests will be suspendedsession_start()
Until the session file is unlocked.
solve:
Since the locked session file will not be unlocked until the script is executed or the session is closed normally, in order to prevent a large number of php requests (need to use $_SESSION data) from being locked, you can close it immediately after writing the session, so that the lock is released.
Close session:
session_write_close();
This trick works very well, especially for a script that takes a long time to process. And this function just closes the writing session, and it is OK to read it.
// session_start(); //You can read and write session$_SESSION['latestRequestTime'] = time(); //Close sessionsession_write_close(); //Read session$twitterId = $_SESSION['twitterId'];
Translator's note:
After php5.4,session_set_save_handler
Supported deliverySessionHandlerInterfaceThe second parameter is to specifysession_write_close()
As a callback method (by default, true), the function issession_write_close()
Register asregister_shutdown_function()
function.
Using Memcache or Redis to store sessions can solve the problem of "locking", but poor handling will lead to the elevation of the connection number (if there is a time-consuming operation after the session operation, the connection will not be recycled. You can actively do it after the session write operation is completed.session_write_close()
operate)
For more information about PHP related content, please check out the topic of this site:Summary of php cache technology》、《Complete collection of PHP array (Array) operation techniques》、《Introduction to PHP basic syntax》、《Summary of PHP operations and operator usage》、《Summary of PHP network programming skills"and"Summary of usage of php strings》
I hope this article will be helpful to everyone's PHP programming.