第 29 章 - ES 源码篇 - 网络 IO 模型及其实现概述

前言

本文介绍了 ES 使用的网络模型,并介绍 transport,http 接收、响应请求的代码入口。

网络 IO 模型

Node 在初始化的时候,会创建网络模块。网络模块会加载 Netty4Plugin plugin。

而后由 Netty4Plugin 创建对应的 transports,以及 http server。

代码分别入口为:Netty4Plugin#getTransportsNetty4Plugin#getHttpTransports

众所周知,Netty 中使用的网络 IO 模型是 主从 Reactor。

接下来带大家一起看创建的细节。

Transport

代码入口为构造函数 Netty4Transport

因为 transport 主要用于内部,因此既有 ServerBootstrap,又有 Bootstrap
ServerBootstrapNetty 中表示 Server 的类。
BootstrapNetty 中表示 Client 的类。

ES 使用的是 NioEventLoopGroup,其底层实现基于 Java NIO

JAVA NIO 在不同的平台上,会执行不同的系统调用。例如,在 Linux(2.6之后) 会使用 epoll

创建 NioEventLoopGroup 的代码入口为:SharedGroupFactory#getGenericGroup(),默认会创建 Runtime.availableProcessors()EventLoop(工作线程),可通过 transport.netty.worker_count 修改创建的个数。

其中,Server 和 Client 会共用同一个 NioEventLoopGroup。代码入口 Netty4Transport#doStart()

接收请求代码入口:
Netty4MessageChannelHandler#channelRead(ChannelHandlerContext ctx, Object msg)

响应请求代码入口:
Netty4MessageChannelHandler#write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)

http server

创建

代码入口为构造函数 Netty4HttpServerTransport。在 doStart() 函数中描述了 ServerBootstrap 的创建过程。

默认情况下 http server 和 transport 共用同一个 NioEventLoopGroup。如果想改变这个行为,需要设置 http.netty.worker_count 的值大于 0。描述这段逻辑的代码入口为:SharedGroupFactory#getHttpGroup()

接收 http 请求

接收请求的入口为:Netty4HttpRequestHandler#channelRead0(ChannelHandlerContext ctx, HttpPipelinedRequest httpRequest)

与我们所熟知的 MVC 框架类似,请求进来后,都会交由某个类去做请求的分发。在 ES 中,负责分发请求的类为:RestController#dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext)

不同的请求可能会运行在不同的业务线程上。

响应 http 请求

响应 http 请求的入口为: Netty4HttpResponseCreator#encode
Netty4HttpResponseCreator 继承的是 Netty 的 MessageToMessageEncoder 类。该类在可以写就绪时,会自动调用 write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) 方法,而 write 方法中则会调用 encode 方法,因此这里说,入口是 encode 方法。

本文由mdnice多平台发布

相关推荐
爬山算法9 分钟前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment26 分钟前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte1 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行2 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple2 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东3 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble3 小时前
springboot的核心实现机制原理
java·spring boot·后端
全栈老石3 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
space62123273 小时前
在SpringBoot项目中集成MongoDB
spring boot·后端·mongodb
Tony Bai4 小时前
再见,丑陋的 container/heap!Go 泛型堆 heap/v2 提案解析
开发语言·后端·golang