Redis is a single process single-threaded server that is implemented using multiple IO multiplexing technology, that is, event-based.
Redis are divided into two types of events, file time and time events.
File events: The traditional IO operation, basically divided into connection, read, write and shutdown.
Different clients send a variety of requests, the Redis multiplexing program will decompose the request into different events, and then package the socket and event into the queue, to the event separator processing, the event separator will give each event to the corresponding processor processing. The process is shown below:
IO multiplexing programs listen for different sockets and pack them into queues whenever an event occurs:
Finally to the separator to spend, you can see here is the order of execution, this is the reason Redis can do distributed locks, distributed programs will eventually be queued here in Redis.
Below, look at the processor for the Redis file event. There are three main categories.
The answering processor, primarily the encapsulation of the accept function, is the type of event that is connected, and once a connection occurs, the processor creates a socket and adds a new event listener and corresponding processor to the socket.
Command request processor, when the client called write, that is, sent the command, then the server to read the command, the corresponding event type is read, is the underlying socket read function encapsulation, read the command, put in the buffer, let the following command executor to execute the corresponding command.
Command answering processor that triggers when the client executes read waiting for the server to return results, the corresponding event type is write, the encapsulation of the underlying socket write function, the server executes the client's request, and the result is returned.
So, a complete Redis request is:
Time Event:
There are two types, one is timed event, only one is executed, the other is periodic event, execution multiple times
There are three attributes for the time event: Id,when,handler
The server maintains a list of time events, and the pointer is time_events.
The service side then has a processtimeevents function that periodically iterates through the list of time events and, if necessary, executes the handler for the event, and then, if it is a cyclical event, updates the event's when and adds it to the list again. Otherwise, throw out the list:
With regard to time events, a very important function within Redis is the periodic execution of the Servercron function, which will:
It can be said that it is a periodic time event of the processing function.