PHP session file exclusive lock causes blocking problem solution
This article mainly introduces the blocking caused by the exclusive lock of the PHP session file. This article describes how to solve the blocking problem easily caused by the use of the default file session processor in PHP. For more information, see
The default session processor of PHP is session. save_handler = files ). If the same client sends multiple requests concurrently (for example, ajax sends multiple requests simultaneously on the page) and the script execution takes a long time, the session file will be blocked and the performance will be affected. For each request, PHP executes session_start () to obtain the exclusive file lock. The exclusive lock is released only after the request is processed. In this way, multiple requests at the same time will cause blocking. The solution is as follows:
(1) After modifying the session variable, use session_write_close () to save the session data and release the filelock.
?
1 2 3 4 5 6 |
Session_start (); $ _ SESSION ['test'] = 'test '; Session_write_close (); // Do something |
(2) Use the session_set_save_handler () function to implement custom session processing.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
Function open ($ savePath, $ sessionName) { Echo 'open is called '; Return true; } Function close () { Echo 'close is called '; Return true; } Function read ($ sessionId) { Echo 'read is called '; Return ''; } Function write ($ sessionId, $ data) { Echo 'write is called '; Return true; } Function destroy ($ sessionId) { Echo 'Destroy is called '; Return true; } Function gc ($ lifetime) { Echo 'gc is called '; Return true; } Session_set_save_handler ("open", "close", "read", "write", "destroy", "gc "); Register_shutdown_function ('session _ write_close '); Session_start (); $ _ SESSION ['foo'] = "bar "; |
Of course, after php 5.4.0, you can use it by implementing the SessionHandlerInterface interface or inheriting the SessionHandler class.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
Class MySessionHandler extends SessionHandler { Public function _ construct () { } Public function open ($ save_path, $ session_id) { } Public function close () { } Public function create_sid () { } Public function read ($ id) { } Public function write ($ id, $ data) { } Public function destroy ($ id) { } } $ Handler = new MySessionHandler (); // Register the session_write_close () function as the register_shutdown_function () function with the 2nd parameters. Session_set_save_handler ($ handler, true ); |
You can implement and encapsulate the above Code and use mysql or other memory databases to manage session data. Cluster
Session data sharing issues.