This article will take you to quickly understand the thread IO model in Redis
Redis is single-threaded, but why is it so fast? One reason is that redis uses non-blocking IO and multiplexing to handle a large number of client connections. The following article will take you to understand the thread IO model in Redis. I hope it will be helpful to you!
Redis is a single-threaded application. NodeJs and Nginx are both single-threaded. They are all models of high-performance servers. [Related recommendations: Redis Video Tutorial]
The reason why Redis is single-threaded and so fast:
Firstly, because all its data is in memory All operations are memory-level operations, so when using redis, pay attention to instructions with a time complexity of O(n). Because it is single-threaded, if the amount of data is too large, other instructions will be blocked and wait;
The second reason is that redis uses non-blocking IO and multiplexing to handle a large number of client connections.
Non-blocking IO
When we use the read and write methods of the socket, the default is blocking,
That is, calling the read method to pass a parameter n, indicating the maximum number of reads Return after taking n bytes. If there is not a byte, the thread will continue to wait in the read method until data comes or the connection is closed. The read method returns at this time and the thread can execute the following logic,
The write method generally does not block. Unless the write buffer allocated by the kernel for the socket is full, the write method will block until there is free space in the buffer.
The following figure is the detailed process of socket reading and writing.
Non-blocking IO provides an option Non_Blocking when using sockets. When this option is turned on, the read and write methods will not block, but can read as much as they can. , write as much as you can,
How much you can read depends on the number of data bytes in the read buffer allocated by the kernel for the socket, and how much you can write depends on the data allocated by the kernel on the write buffer of the socket. Number of bytes,
The read and write methods will tell the program how many bytes have been read and written through the return value.
Non-blocking IO means that the thread no longer has to be blocked when reading and writing. Reading and writing can be completed instantly, and the thread can continue to do other things.
Multiplexing (event polling)
Although non-blocking IO is very fast, it also brings a problem. The thread reads the data and returns after reading part of it. It has not finished reading. When will the remaining data continue to be read? , writing data, the buffer is full and has not been written completely. When will the remaining data continue to be written?
When you can continue to read or continue to write, you should give the application a notification to tell the application that you can continue to read or continue to write. The event polling API is used to handle this problem.
select
The operating system provides a select function for the user program. The input is the read and write descriptor list read_fds & write_fds, and the output is The corresponding readable and writable events,
also provide the timeout parameter, the thread can wait for the timeout at most. During this period, if an event comes, the method will return immediately, and the thread will continue processing. If the timeout time is exceeded, The method will also return.
If the event is obtained, the thread can process the corresponding events one by one. After processing, it will continue to call the select api polling, so the thread is actually an infinite loop and keeps selecting. Non-stop processing, back and forth, this endless loop is called an event loop, and a loop is a cycle.
Event loop pseudocode:
while True read_events, write_events = select(read_fds, write_fds, timeout) for event in read_events: handle_read(event.fd) for event in write_events: handle_write(event.fd) handle_others() # 做其他的逻辑处理,处理定时任务等等
Through the select function we can handle the read and write events of multiple channel descriptors, so systems like select will The function call is called multiplexing API.
The multiplexing API of modern operating systems no longer uses the select system call, but uses epoll (linux) and kqueue (FreeBSD, macosx) instead.
The performance of select will become very poor when the number of descriptors increases. There are slight differences in the use of epoll and select, but they can be understood using the above pseudocode. When an event occurs on the descriptor, the descriptor will be looped. The event is processed. The read operation of the
serversocket object refers to calling accept to accept a new connection from the client. When a connection comes, it is also notified through the read event called by select.
The NIO technology in Java is event polling, and other languages also have this technology.
Command Queue
Redis associates a command queue with each client socket, and the commands sent by the client are processed in first-in, first-out order through the queue.
Response Queue
Similarly, the results returned by Redis are also returned through a queue associated with each client. If the queue is empty, there is no need to obtain write events for the time being,
At this time, the client descriptor will be removed from write_fds, and when the queue has data, the descriptor will be put in. This can avoid finding that there is no data to write when the select system call returns the write event, causing empty space. Polling, useless polling, consumption of machine CPU.
Timing tasks
The server not only needs to respond to IO events, but also needs to handle some other things, such as the application's own timing tasks. If the thread blocks on the select call, waiting for the return of select, this will cause Some scheduled tasks have expired but have not been executed.
Redis’ scheduled tasks are recorded in a data structure called the minimum heap. In this heap, the fastest tasks to be executed are ranked at the top. Each cycle During the cycle, redis will process the tasks in the heap that have reached the time point.
After the processing is completed, the time required for the tasks to be executed in the heap will be recorded. When select is called again, this time will be The value of timeout means that no other tasks will need to be executed during this period. Redis can safely block for this long at most, and then perform corresponding processing after the time is up.
The event processing principles of NodeJs and Nginx are similar to Redis.
For more programming related knowledge, please visit: Programming Video! !
The above is the detailed content of This article will take you to quickly understand the thread IO model in Redis. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information
