Nginx exactly how to handle events?

In the understanding of network events and event distribution collector later, let us know Nginx is how to deal with incidents?

Nginx event loop

Nginx event loop

When Nginx has just started, the wait for the event section, which is open 80 or port 443, this time came in an event waiting for a new, such as a new client even on the Nginx to us to initiate a connection, this step often correspond to epoll epoll wait method, this time Nginx is actually in the process of such a state of sleep. When the operating system has received a TCP connection is established and after the handshake packets processed handshake process, the operating system will notify the epoll wait this blocking method, you can tell it to go down, and wake-up Nginx worker processes.

After then go down, it will go to the operating system to ask for an event, the operating system will he ready events on the event queue from the event queue can get in to the event need to be addressed. For example, to establish a TCP connection request or receive messages.

Nginx a loop handle events

取出以后就会进行循环处理事件,如上就是处理事件的一个循环:当发现队列中不为空,就把事件取出来开始处理事件;在处理事件的过程中,可能又生成新的事件,比如说发现一个连接新建立了,可能要添加一个超时时间,比如默认的 60 秒,也就是说 60 秒之内如果浏览器不向 Nginx 发送请求的话,Nginx 就会把这个连接关掉;又比如说当 Nginx 发现已经收完了完整的 HTTP 请求以后,可以生成 HTTP 响应了,那么这个生成响应是需要 Nginx 可以向操作系统的写缓存中心里面去把响应写进去,要求操作系统尽快的把这样一段响应内容发到浏览器上,也就是说可能在处理过程中可能会产生新的事件,就是循环处理事件部分指向的事件队列部分,等待下一次来处理。

如果所有的事件都处理完成以后呢,又会返回到等待事件部分。

在学习了 Nginx 事件循环后,我们再去理解,有时候使用一些第三方模块,这些第三方模块可能会做大量的 CPU 运算,这样的计算任务会导致处理一个事件的时间非常的长;在上面的一个流程图中,可以看到会导致队列中的大量事件会长时间得不到处理,从而引发恶性循环,也就是他们的超时时间可能到了;大量的 CPU、Nginx 的任务都消耗在处理连接不正常的断开,所以 Nginx 不能容忍有些第三方模块长时间的消耗大量的 CPU 进行计算任务就是这样一个原因。我们可以看到像 GZIP 这样的模块,他们都不会在一次使用大量的 CPU 而是分段使用,这些都与 Nginx 的事件循环有关的。

总结

This article explains how to Nginx is a major event and handle the event loop processes Nginx is kind of how, explain how to pave the way for the next event loop process is Nginx get events waiting to be processed from the operating system, and by the event loop learn why a large number of computing tasks Nginx does not expect the emergence of third-party CPU module.

Guess you like

Origin www.cnblogs.com/wupeixuan/p/12150943.html