Request MethodNginx is a high-performance Web server that handles a large number of concurrent requests, mainly thanks to Nginx Master-worker process patterns and asynchronous mechanisms.
Master-worker Mode
NIGNX server for each request received, the main process master generates a worker process (worker processes) processing. After the worker process reads to this client request event, it calls the back-end I/O for processing. For the number of worker processes, certainly not the more the better. Because there are too many processes, it can cause CPU switching and scheduling, which wastes resources. Typically, the number of worker processes is equal to the kernel number of the server CPU. The benefit of doing so is to avoid excessive worker processes competing for CPU resources. Worker processes are independent of each other, so the design avoids the performance overhead of competing for the same lock. Once a process has exited unexpectedly, it does not affect other processes working correctly.
asynchronous non-blocking
When a worker process receives a client request, it invokes the I/O process directly, and if the result is not immediately available, it handles something else. When I/O processing is complete, the worker process is notified and the worker process is notified to suspend the current processing to respond to the client.
Event-DrivenThe Nignx event-driven model is mainly divided into event collectors, event senders, and event handlers. When the event collector reads various I/O requests to the worker, it is processed by the event dispatcher, which sends the requested request to the event handler for processing. Event handlers are really responsible for various I/O events, and the event handlers are designed with multiplexing mode.
The
Main model relationships are as follows:
Request principle Nginx works in the Master-worker process mode, that is, a master process, multiple worker child processes. For client-sent requests client-request, only one worker process can be processed, how multiple worker processes compete for client client-request requests.
When the Nginx server is started, the master process creates a listen socket file descriptor, that is, LISTENFD. The fork () function is then invoked to create the subprocess worker process. The worker process needs to obtain the Accept_mutex mutex in the master process before it reads the client request, and only the worker process that obtains the Accept_mutex lock can register the LISTENFD event. That is, by invoking the Accept method to receive client requests, parsing requests, processing requests, and so on.