Why Netty
Java 原生 NIO 的缺点
上一篇文章 NIO 概览 里已经说过了,直接转过来:Java 原生 NIO 编程的缺点。
NIO 框架选型
我听说过的 NIO 框架有下面几种:
Mina
Netty
Grizzly(Sun GlassFish Application Server 底层NIO框架)
Tomcat NIO
xSocket(已停止维护)
但是都不熟悉,就没法拿测试数据来对比性能、稳定性等等指标。不过有一点是毫无疑问的,Netty 应用面是最广的。Netty 官网的 Adopters 上,基本包含了国内外说的上号的互联网公司。
选它准没错。
Netty
Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.
Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server.
‘Quick and easy’ doesn’t mean that a resulting application will suffer from a maintainability or a performance issue. Netty has been designed carefully with the experiences earned from the implementation of a lot of protocols such as FTP, SMTP, HTTP, and various binary and text-based legacy protocols. As a result, Netty has succeeded to find a way to achieve ease of development, performance, stability, and flexibility without a compromise.
Netty components
Design
- Unified API for various transport types - blocking and non-blocking socket
- Based on a flexible and extensible event model which allows clear separation of concerns
- Highly customizable thread model - single thread, one or more thread pools such as SEDA (Staged Event-Driven Architecture)
- True connectionless datagram socket support (since 3.1)
Performance
- Better throughput, lower latency
- Less resource consumption
- Minimized unnecessary memory copy
用官方的话来说就是:Netty是一个异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。
简言之,Netty封装了JDK的NIO,让你用得更爽。
- asynchronous - 异步,不仅仅是异步 IO(NIO,读写不阻塞线程),且所有 IO 操作都是异步进行的(Future、Promise)
- event-driven - 事件驱动:事件产生,事件处理,事件流转 ChannelPipeline、ChannelHandlerContext、ChannelHandler
- high performance - Reactor 模型(multiple reactor threads),并发编程,避免切换线程 EventLoop
- protocol - 实现了各种协议,当然包括底层的粘包、拆包 ByteToMessageDecoder
- Zero-copy - 不是系统层面的内核态(Kernel-space) 与 用户态(User-space) 之间的来回拷贝。Netty的 Zero-coyp 完全是在用户态(Java 层面)的, Zero-copy 更多的是说明尽量减少拷贝。
Netty 示例
EchoServer
EchoServer
1 | public final class EchoServer { |
EchoServerHandler
1 |
|
终端上创建 3 个 client
1 | nc 127.0.0.1 7777 |
EchoServer 打印日志如下,可以找到 Multiple Reactor Threads 模型
1 | [INFO ][2019-02-15 16:36:28,704][nioEventLoopGroup-3-1](AbstractInternalLogger.log:150) - [id: 0xb265683b] REGISTERED |
EchoClient
EchoClient
1 | public final class EchoClient { |
EchoClientHandler
1 |
|
参考
本文参考了互联网上大家的分享,就不一一列举,在此一并谢过。
也希望本文,能对大家有所帮助,若有错误,还请谅解、指正。