I talked with my colleagues yesterday Redis, He asked me Redis How are you doing , I said learning is OK , Then he suddenly asked “ You know, Redis Is multithreading supported now ？”, I was stunned for a moment ,Redis It's always single threaded , How to support multithreading all of a sudden ？ The moment is felt by the second , Come back and look up the relevant information , Otherwise, I dare not say that I will Redis 了
So let's go back Redis Single thread mode related knowledge , We all know Redis The main reason for being fast is because epool I/O Reuse model , Let's talk about it briefly ：
The picture below is Redis The internal core flow chart of （ It's also a classic introduction I can find Redis The schematic diagram of ）, In fact, the internal is mainly realized through two-way queue and red black tree （ The pictures are very detailed , What you don't know in it , Baidu can be directly , Easy to find ）：
For a request operation ,Redis Mainly do 3 thing ： Read data from client 、 perform Redis command 、 Write back the data to the client （ If it's more accurate , In fact, it also includes the analysis of the protocol ）. So the main thread is actually to put all the operations of this 3 thing , Serial execution together , Because it's memory based , So the execution speed is very fast ：
advantage VS shortcoming ：
Redis Multithreading optimization ideas ： Because of the Internet I/O stay Redis It takes up most of the time CPU Time , So the Internet I/O Part of it comes out alone , Make it multithreaded .
Multithreading here , It's really just the Redis These two things are done in a single thread “ Read data from client 、 Write back the data to the client ”（ It can also be called the Internet I/O）, It's multithreaded , however “ perform Redis command ” Or serial execution in the main thread , The logic remains the same .
Maybe some students will ask , Main thread and multiple I/O Threads , All of them deal with the data in the graph at the same time “ queue ”, Will there be lock competition ？ Here's a clever design , Is that when epoll obtain socket When linking , The event will be thrown into the queue first , Like throwing it away N Events , At this time, the main thread will be busy and so on (spinlock Spin lock effect ) state . And then many I/O Threads start to network in parallel I/O, And analyze the data protocol , When all the queues have been processed , The main thread serializes the requests in the queue ““ perform Redis command ”, Then clear the queue . So the whole execution process is summed up ： The main thread queues the request -> I/O Thread parallel network read -> The main thread executes serially Redis command -> I/O Thread parallel network write -> The main thread clears the queue , And receive the next batch of requests .
advantage VS shortcoming
Welcome to like it more , More articles , Please follow the WeChat public account “ Louzi's way to advancement ”, Focus , Neverlost ~~