lzh2nix / articles

用 issue 来管理个人博客
https://github.com/lzh2nix/articles
63 stars 13 forks source link

redis 5.0 socket事件处理框架 #136

Open lzh2nix opened 3 years ago

lzh2nix commented 3 years ago

redis是一款以快著称的内存数据库,内置里很多的数据结构方便开发者直接使用。就如他名字里RemoteDictSever中提到的remote server,我们一般都是redis跑在一批机器上然后应用服务通过socket和他进行通信。这里就来看看redis是如何处理网络请求的。

处理网络请求通常有两种模式 多线程模式和事件驱动模式, 前者对每个请求创建一个线程去处理请求,而后者中只使用少量的线程,在线程中while loop等待事件的发生,之后会通过回调等形式通知关联方。redis采用的是事件驱动的模式, 更具体的说redis是采用事件驱动中的reactor模式, 以下reactor作者对reacotr的描述。

The Reactor design pattern handles service requests that are delivered concurrently to an application by one or more clients. Each service in an application may consist of serveral methods and is represented by a separate event handler that is responsible for dispatching service-specific requests. Dispatching of event handlers is performed by an initiation dispatcher, which manages the registered event handlers. Demultiplexing of service requests is performed by a synchronous event demultiplexer.

可以看到reactor模式主要由Dispatching,Demultiplexer和各种Handler组成。以下是reids中的reactor模型。 image

代码逻辑

image