Redis uses a memory-based KV database that uses a single-process single-thread model and is written in C language. The official data provided is that it can reach 100,000 qps. This data is no worse than Memcached, the same memory-based KV database that uses single process and multi-threading.
The main reasons why Redis is fast are:
1. Completely based on memory
2. The data structure is simple and the data operations are also simple
3. Use multi-channel I/O multiplexing model
I won’t go into details on the first and second points, but mainly focus on the third point using multi-channel I/O multiplexing technology.
The multi-channel I/O multiplexing model uses select, poll, and epoll to monitor the I/O events of multiple streams at the same time. When idle, the current thread will be blocked. When there is a When there are I/O events in multiple streams, they will wake up from the blocking state, so the program will poll all the streams (epoll only polls those streams that actually emitted events), and will only process them sequentially. Stream, this approach avoids a lot of useless operations. Here "multiple" refers to multiple network connections, and "reuse" refers to reusing the same thread. The use of multi-channel I/O multiplexing technology allows a single thread to efficiently handle multiple connection requests (minimizing the time consumption of network IO), and Redis operates data in memory very quickly (in-memory operations will not become a problem here). Performance bottleneck), the above two points mainly contribute to the high throughput of Redis.
Unlike Memcached, Redis does not use Libevent directly, but completes a very lightweight implementation of common interfaces such as select, epoll, evport, and kqueue. Choose the appropriate interface for different system calls. The default under Linux is epoll. Because Libevent is relatively heavy and general-purpose, the amount of code is very large, and it has many functions that Redis cannot use. In order to pursue "lightness" and remove dependencies, Redis chose to encapsulate it itself.
Benefits of single process and single thread
1. The code is clearer and the processing logic is simpler.
2. There is no need to consider various lock issues. There is no locking and releasing lock operations, and there is no performance consumption caused by possible deadlocks.
3. There is no CPU consumption due to switching caused by multi-process or multi-thread.
The above is the detailed content of Why is redis so fast. For more information, please follow other related articles on the PHP Chinese website!