Using fastcgi_ finish_ Request to achieve asynchronous processing and improve the response speed of the page

After chopping hands, the fraud call came before the express delivery was received. How to improve the privacy and security of e-commerce>>>

fastcgi_ finish_ Request () is to flush all response data to the client and end the request. This allows tasks that need a lot of time to continue to run after the client ends the connection

When PHP is running in fastcgi mode, PHP FPM provides a file named fastcgi_ finish_ According to the document, this method can improve the processing speed of the request. If some processing can be done after the page is generated, you can use this method.

it may sound a little confused. Let’s illustrate it with a few examples:

The code is as follows Copy code
<?PHP

echo ‘example:’
fastcgi_ finish_ request(); /* When the response is completed, close the connection */

/* log */
file_ put_ To be or not to be is a question
?>

Through the browser to access the script, it is found that the corresponding string is not output, but the corresponding file is generated. This shows that when calling fastcgi_ finish_ Request, the client response has ended, but at the same time, the server script continues to run

rational use of this feature can greatly improve the user experience. Strike while the iron is hot: another example:

The code is as follows Copy code
<?PHP

echo ‘example:’

file_ put_ Contents (‘log. TXT ‘, date (‘y-m-d H: I: s’)_ APPEND);

fastcgi_ finish_ request();

sleep(1);
file_ put_ Contents (‘log. TXT ‘, date (‘y-m-d H: I: s’)_ APPEND);

sleep(1);
file_ put_ Contents (‘log. TXT ‘, date (‘y-m-d H: I: s’)_ APPEND);

?>

in the code, sleep is used to simulate some time-consuming operations. When browsing, the program is not blocked, but it is executed. See the log for details.

finally, to remind you, Yahoo mentioned “flush the buffer early” in the best practices for speeding up your web site, that is, using the flush method in PHP to send the content to the client as soon as possible, which is similar to fastcgi introduced in this article_ finish_ In addition, in terms of code portability, the following code can be attached to the code:

The code is as follows Copy code
if (! function_ exists(“fastcgi_ finish_ request”)) {
function fastcgi_ finish_ request() {
}
}

Similar Posts: