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 reason why Redis is fast is: (Recommended learning: Redis video tutorial)
Completely based on memory
Data structure Simple, and easy to operate data
Use multi-channel I/O multiplexing model
I won’t go into details about the first and second points, but mainly focus on the third point to use multi-channel I/O O Reuse technology to expand.
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 one or more streams have I/O events, they will wake up from the blocking state, so the program will poll all streams (epoll only polls those streams that actually emitted events), and only in sequence Processing ready streams, 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 appropriate interfaces 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
The code is clearer and the processing logic is simpler
There is no need to consider various lock issues, there is no locking Release lock operation, there is no performance consumption caused by possible deadlock
There is no switching caused by multi-process or multi-thread that consumes CPU performance
Disadvantages of single process and single thread
Cannot take advantage of multi-core CPU performance, but it can be improved by opening multiple Redis instances on a single machine;
The above is the detailed content of Why is redis single process fast?. For more information, please follow other related articles on the PHP Chinese website!