netty教程

测试代码Github地址:https://github.com/zhouyanger/java_demo/tree/master/netty

四.Netty

4.1 概述

Netty 是由 JBOSS 提供的一个 Java 开源框架。Netty 提供异步的、基于事件驱动的网络

应用程序框架,用以快速开发高性能、高可靠性的网络 IO 程序。

Netty 是一个基于 NIO 的网络编程框架,使用 Netty 可以帮助你快速、简单的开发出一

个网络应用,相当于简化和流程化了 NIO 的开发过程。

作为当前最流行的 NIO 框架,Netty 在互联网领域、大数据分布式计算领域、游戏行业、

通信行业等获得了广泛的应用,知名的 Elasticsearch 、Dubbo 框架内部都采用了 Netty。

 netty教程

 

4.2 Netty 整体设计

4.2.1 线程模型

1. 单线程模型

netty教程

服务端用一个线程通过多路复用搞定所有的io操作(包括连接,读,写等),编码简单,但如果客户端数量较多,将无法支撑,前面的nio就是该模型。

2. 线程池模型

netty教程

服务器端采用一个线程专门处理客户端连接请求,采用一个线程池负责 IO 操作。在绝

大多数场景下,该模型都能满足使用。

3. Netty 模型

 netty教程

比较类似于上面的线程池模型,Netty 抽象出两组线程池,BossGroup 专门负责接收客

户端连接,WorkerGroup 专门负责网络读写操作。NioEventLoop 表示一个不断循环执行处理 任务的线程,每个 NioEventLoop 都有一个 selector,用于监听绑定在其上的 socket 网络通道。 NioEventLoop 内部采用串行化设计,从消息的读取->解码->处理->编码->发送,始终由 IO 线 程 NioEventLoop 负责。

一个 NioEventLoopGroup 下包含多个 NioEventLoop

每个 NioEventLoop 中包含有一个 Selector,一个 taskQueue

每个 NioEventLoop 的 Selector 上可以注册监听多个 NioChannel

每个 NioChannel 只会绑定在唯一的 NioEventLoop 上

每个 NioChannel 都绑定有一个自己的 ChannelPipeline

4.2.2 异步模型

l FUTURE, CALLBACK 和 HANDLER

Netty 的异步模型是建立在 future 和 callback 的之上的。callback 大家都比较熟悉了,这

里重点说说 Future,它的核心思想是:假设一个方法 fun,计算过程可能非常耗时,等待 fun

返回显然不合适。那么可以在调用 fun 的时候,立马返回一个 Future,后续可以通过 Future

去监控方法 fun 的处理过程。

在使用 Netty 进行编程时,拦截操作和转换出入站数据只需要您提供 callback 或利用

future 即可。这使得链式操作简单、高效, 并有利于编写可重用的、通用的代码。Netty 框

架的目标就是让你的业务逻辑从网络基础应用编码中分离出来、解脱出来。

4.3 核心 API

l ChannelHandler 及其实现类

ChannelHandler 接口定义了许多事件处理的方法,我们可以通过重写这些方法去实现具

体的业务逻辑。API 关系如下图所示:

 netty教程

我们经常需要自定义一个 Handler 类去继承 ChannelInboundHandlerAdapter,然后通过

重写相应方法实现业务逻辑,我们接下来看看一般都需要重写哪些方法:

Ø public void channelActive(ChannelHandlerContext ctx),通道就绪事件

Ø public void channelRead(ChannelHandlerContext ctx, Object msg),通道读取数据事件

Ø public void channelReadComplete(ChannelHandlerContext ctx) ,数据读取完毕事件

Ø public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause),通道发生异常

事件

l Pipeline ChannelPipeline

ChannelPipeline 是一个 Handler 的集合,它负责处理和拦截 inbound 或者 outbound 的事 件和操作,相当于一个贯穿 Netty

 netty教程

Ø ChannelPipeline addFirst(ChannelHandler... handlers),把一个业务处理类(handler)添加 到链中的第一个位置

Ø ChannelPipeline addLast(ChannelHandler... handlers),把一个业务处理类(handler)添加

到链中的最后一个位置

l ChannelHandlerContext

这 是 事 件 处 理 器 上 下 文 对 象 , Pipeline 链 中 的 实 际 处 理 节 点 。 每 个 处 理 节 点

ChannelHandlerContext 中 包 含 一 个 具 体 的 事 件 处 理 器 ChannelHandler , 同 时 ChannelHandlerContext 中也绑定了对应的 pipeline 和 Channel 的信息,方便对 ChannelHandler 进行调用。常用方法如下所示:

Ø ChannelFuture close(),关闭通道

Ø ChannelOutboundInvoker flush(),刷新

Ø ChannelFuture writeAndFlush(Object msg) , 将 数 据 写 到 ChannelPipeline 中 当 前

ChannelHandler 的下一个 ChannelHandler 开始处理(出站)

l ChannelOption

Netty 在创建 Channel 实例后,一般都需要设置 ChannelOption 参数。ChannelOption 是

Socket 的标准参数,而非 Netty 独创的。常用的参数配置有:

1. ChannelOption.SO_BACKLOG

对应 TCP/IP 协议 listen 函数中的 backlog 参数,用来初始化服务器可连接队列大小。服

务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。多个客户 端来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog 参数指定了队列的大小。

2. ChannelOption.SO_KEEPALIVE ,一直保持连接活动状态。

l ChannelFuture

表示 Channel 中异步 I/O 操作的结果,在 Netty 中所有的 I/O 操作都是异步的,I/O 的调 用会直接返回,调用者并不能立刻获得结果,但是可以通过 ChannelFuture 来获取 I/O 操作 的处理状态。

常用方法如下所示:

Ø Channel channel(),返回当前正在进行 IO 操作的通道

Ø ChannelFuture sync()  等待异步操作执行完毕

l EventLoopGroup 和其实现类 NioEventLoopGroup

EventLoopGroup 是一组 EventLoop 的抽象,Netty 为了更好的利用多核 CPU 资源,一般

会有多个 EventLoop 同时工作,每个 EventLoop 维护着一个 Selector 实例。

EventLoopGroup 提供 next 接口,可以从组里面按照一定规则获取其中一个 EventLoop

来处理任务。在 Netty 服务器端编程中,我们一般都需要提供两个 EventLoopGroup,例如:

BossEventLoopGroup 和 WorkerEventLoopGroup。

通常一个服务端口即一个 ServerSocketChannel对应一个Selector 和一个EventLoop线程。BossEventLoop 负责接收客户端的连接并将 SocketChannel 交给 WorkerEventLoopGroup 来进 行 IO 处理,如下图所示:

 netty教程

BossEventLoopGroup 通常是一个单线程的 EventLoop,EventLoop 维护着一个注册了

ServerSocketChannel 的 Selector 实例,BossEventLoop 不断轮询 Selector 将连接事件分离出来, 通常是 OP_ACCEPT 事件,然后将接收到的 SocketChannel 交给 WorkerEventLoopGroup, WorkerEventLoopGroup 会由 next 选择其中一个 EventLoopGroup 来将这个SocketChannel 注 册到其维护的 Selector 并对其后续的 IO 事件进行处理。

常用方法如下所示:

Ø public NioEventLoopGroup(),构造方法

Ø public Future<?> shutdownGracefully(),断开连接,关闭线程

l ServerBootstrap Bootstrap

ServerBootstrap 是 Netty 中的服务器端启动助手,通过它可以完成服务器端的各种配置;

Bootstrap 是 Netty 中的客户端启动助手,通过它可以完成客户端的各种配置。常用方法如下所示:

Ø public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup),

该方法用于服务器端,用来设置两个 EventLoop

Ø public B group(EventLoopGroup group) ,该方法用于客户端,用来设置一个 EventLoop

Ø public B channel(Class<? extends C> channelClass),该方法用来设置一个服务器端的通道

实现

Ø public <T> B option(ChannelOption<T> option, T value),用来给 ServerChannel 添加配置

public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value),用来给接

收到的通道添加配置

Ø public ServerBootstrap childHandler(ChannelHandler childHandler),该方法用来设置业务

处理类(自定义的 handler)

Ø public ChannelFuture bind(int inetPort) ,该方法用于服务器端,用来设置占用的端口号

Ø public ChannelFuture connect(String inetHost, int inetPort) ,该方法用于客户端,用来连

接服务器端

l Unpooled

这是 Netty 提供的一个专门用来操作缓冲区的工具类,常用方法如下所示:

Ø public static ByteBuf copiedBuffer(CharSequence string, Charset charset),通过给定的数据

和字符编码返回一个 ByteBuf 对象(类似于 NIO 中的 ByteBuffer 对象)

4.4 入门案例

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.8.Final</version>
</dependency>
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.10</version>
</dependency>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.6.1</version>
</dependency>

定义服务端

//自定义服务器端业务处理类

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

@Override //读取数据事件

public void channelRead(ChannelHandlerContext ctx, Object msg) {

System.out.println("Server: " + ctx);

ByteBuf buf = (ByteBuf) msg;

System.out.println("客户端发来的消息 : " + buf.toString(CharsetUtil.UTF_8));

}

@Override //数据读取完毕事件

public void channelReadComplete(ChannelHandlerContext ctx) {

ctx.writeAndFlush(Unpooled.copiedBuffer("就是没钱", CharsetUtil.UTF_8));

}

@Override //异常发生事件

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

cause.printStackTrace();

ctx.close();

}

}

上述代码定义了一个服务器端业务处理类,继承 ChannelInboundHandlerAdapter,并分别重 写了三个方法。

public class NettyServer {

public static void main(String[] args) throws Exception{

//1.创建一个线程组:用来处理网络事件(接受客户端连接)

EventLoopGroup bossGroup = new NioEventLoopGroup();

//2.创建一个线程组:用来处理网络事件(处理通道 IO 操作)

EventLoopGroup workerGroup = new NioEventLoopGroup();

//3.创建服务器端启动助手来配置参数

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup, workerGroup) //4.设置两个线程组 EventLoopGroup

.channel(NioServerSocketChannel.class) //5.使用 NioServerSocketChannel 作为服务器

端通道实现

.option(ChannelOption.SO_BACKLOG, 128) //6.设置线程队列中等待连接的个数

.childOption(ChannelOption.SO_KEEPALIVE, true) //7.保持活动连接状态

.childHandler(new ChannelInitializer<SocketChannel>() { //8.创建一个通道初始化对象

public void initChannel(SocketChannel sc) { //9.往 Pipeline 链中添加自定义的业务

处理 handler

sc.pipeline().addLast(new NettyServerHandler()); //服务器端业务处理类

System.out.println(".......Server is ready.......");

}

});

//10.启动服务器端并绑定端口,等待接受客户端连接(非阻塞)

ChannelFuture cf = b.bind(9999).sync();

System.out.println("......Server is Starting......");

//11.关闭通道,关闭线程池

cf.channel().closeFuture().sync();

bossGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

上述代码编写了一个服务器端程序,配置了线程组,配置了自定义业务处理类,并绑定端口 号进行了启动

//自定义客户端业务处理类

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

@Override

//通道就绪事件

public void channelActive(ChannelHandlerContext ctx) {

System.out.println("Client: " + ctx);

ctx.writeAndFlush(Unpooled.copiedBuffer("老板,还钱吧", CharsetUtil.UTF_8));

}

@Override //通道读取数据事件

public void channelRead(ChannelHandlerContext ctx, Object msg) {

ByteBuf in = (ByteBuf) msg;

System.out.println("服务器端发来的消息 : " + in.toString(CharsetUtil.UTF_8));

}

@Override

//数据读取完毕事件

public void channelReadComplete(ChannelHandlerContext ctx) {

ctx.flush();

}

@Override //异常发生事件

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

ctx.close();

}

}

上述代码自定义了一个客户端业务处理类,继承 ChannelInboundHandlerAdapter ,并分别重写了四个方法。

public class NettyClient {

public static void main(String[] args) throws Exception {

//1.创建一个 EventLoopGroup 线程组

EventLoopGroup group = new NioEventLoopGroup();

//2.创建客户端启动助手

Bootstrap b = new Bootstrap();

b.group(group) //3.设置 EventLoopGroup 线程组

.channel(NioSocketChannel.class) //4.使用 NioSocketChannel 作为客户端通道实现

.handler(new ChannelInitializer<SocketChannel>() { //5.创建一个通道初始化对象

@Override

protected void initChannel(SocketChannel sc) { //6.往 Pipeline 链中添加自定义的业务

处理 handler

sc.pipeline().addLast(new NettyClientHandler()); //客户端业务处理类

System.out.println("......Client is ready.......");

}

});

//7.启动客户端,等待连接上服务器端(非阻塞)

ChannelFuture cf = b.connect("127.0.0.1", 9999).sync();

//8.等待连接关闭(非阻塞)

cf.channel().closeFuture().sync();

}

}

上述代码编写了一个客户端程序,配置了线程组,配置了自定义的业务处理类,并启动连接了服务器端。最终运行效果如下图所示

netty教程

4.5 网络聊天案例

刚才我们通过 Netty 实现了一个入门案例,基本了解了 Netty 的 API 和运行流程,接下

来我们在入门案例的基础上再实现一个多人聊天案例,具体代码如下所示:

//自定义一个服务器端业务处理类

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

public static List<Channel> channels = new ArrayList<>();

@Override //通道就绪

public void channelActive(ChannelHandlerContext ctx) {

Channel incoming = ctx.channel();

channels.add(incoming);

System.out.println("[Server]:"+incoming.remoteAddress().toString().substring(1)+"在线");

}

@Override //通道未就绪

public void channelInactive(ChannelHandlerContext ctx) {

Channel incoming = ctx.channel();

channels.remove(incoming);

System.out.println("[Server]:"+incoming.remoteAddress().toString().substring(1)+"掉线");

}

@Override //读取数据

protected void channelRead0(ChannelHandlerContext ctx, String s) {

Channel incoming = ctx.channel();

for (Channel channel : channels) {

if (channel != incoming){ //排除当前通道

channel.writeAndFlush("[" + incoming.remoteAddress().toString().substring(1) + "]说: " + s

+ "\n");

}

}

}

@Override //发生异常

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

Channel incoming = ctx.channel();

System.out.println("[Server]:"+incoming.remoteAddress().toString().substring(1)+"异常");

ctx.close(); } }

上述代码通过继承 SimpleChannelInboundHandler 类自定义了一个服务器端业务处理类,

并在该类中重写了四个方法,当通道就绪时,输出在线;当通道未就绪时,输出下线;当通道发来数据时,读取数据;当通道出现异常时,关闭通道。

//聊天程序服务器端

public class ChatServer {

private int port; //服务器端端口号

public ChatServer(int port) {

this.port = port;

}

public void run() throws Exception {

EventLoopGroup bossGroup = new NioEventLoopGroup();

EventLoopGroup workerGroup = new NioEventLoopGroup();

try {

ServerBootstrap b = new ServerBootstrap();

b.group(bossGroup, workerGroup)

.channel(NioServerSocketChannel.class)

.childHandler(new ChannelInitializer<SocketChannel>() {

@Override

public void initChannel(SocketChannel ch) {

ChannelPipeline pipeline = ch.pipeline(); //得到 Pipeline 链

//往 Pipeline 链中添加一个解码器

pipeline.addLast("decoder", new StringDecoder());

//往 Pipeline 链中添加一个编码器

pipeline.addLast("encoder", new StringEncoder());

//往 Pipeline 链中添加一个自定义的业务处理对象

pipeline.addLast("handler", new ChatServerHandler());

}

})

.option(ChannelOption.SO_BACKLOG, 128)

.childOption(ChannelOption.SO_KEEPALIVE, true);

System.out.println("Netty Chat Server 启动......");

ChannelFuture f = b.bind(port).sync();

f.channel().closeFuture().sync();

} finally {

workerGroup.shutdownGracefully();

bossGroup.shutdownGracefully();

System.out.println("Netty Chat Server 关闭......");

}

}

public static void main(String[] args) throws Exception {

new ChatServer(9999).run();

}

}

上述代码通过 Netty 编写了一个服务器端程序,里面要特别注意的是:我们往 Pipeline

链中添加了处理字符串的编码器和解码器,它们加入到 Pipeline 链中后会自动工作,使得我

们在服务器端读写字符串数据时更加方便(不用人工处理 ByteBuf)。

//自定义一个客户端业务处理类

public class ChatClientHandler extends SimpleChannelInboundHandler<String> {

@Override

protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {

System.out.println(s.trim());

}

}

上述代码通过继承 SimpleChannelInboundHandler 自定义了一个客户端业务处理类,重

写了一个方法用来读取服务器端发过来的数据。

//聊天程序客户端

public class ChatClient {

private final String host; //服务器端 IP 地址

private final int port; //服务器端端口号

public ChatClient(String host, int port) {

this.host = host;

this.port = port;

}

public void run(){

EventLoopGroup group = new NioEventLoopGroup();

try {

Bootstrap bootstrap = new Bootstrap()

.group(group)

.channel(NioSocketChannel.class)

.handler(new ChannelInitializer<SocketChannel>() {

@Override

public void initChannel(SocketChannel ch){

ChannelPipeline pipeline = ch.pipeline(); //得到 Pipeline 链

//往 Pipeline 链中添加一个解码器

pipeline.addLast("decoder", new StringDecoder());

//往 Pipeline 链中添加一个编码器

pipeline.addLast("encoder", new StringEncoder());

//往 Pipeline 链中添加一个自定义的业务处理对象

pipeline.addLast("handler", new ChatClientHandler());

}

});

Channel channel = bootstrap.connect(host, port).sync().channel();

System.out.println("--------"+channel.localAddress().toString().substring(1)+"--------");

Scanner scanner=new Scanner(System.in);

while (scanner.hasNextLine()) {

String msg=scanner.nextLine();

channel.writeAndFlush(msg + "\r\n");

}

} catch (Exception e) {

e.printStackTrace();

} finally {

group.shutdownGracefully();

}

}

public static void main(String[] args) throws Exception {

new ChatClient("127.0.0.1", 9999).run();

}

}

上述代码通过 Netty 编写了一个客户端程序,里面要特别注意的是:我们往 Pipeline 链

中添加了处理字符串的编码器和解码器,他们加入到 Pipeline 链中后会自动工作,使得我们

在客户端读写字符串数据时更加方便(不用人工处理 ByteBuf)。

我们可以同时运行多个聊天客户端。

4.6 编码和解码

4.6.1 概述

我们在编写网络应用程序的时候需要注意 codec (编解码器),因为数据在网络中传输的

都是二进制字节码数据,而我们拿到的目标数据往往不是字节码数据。因此在发送数据时就

需要编码,接收数据时就需要解码。

codec 的组成部分有两个:decoder(解码器)和 encoder(编码器)。encoder 负责把业务数

据转换成字节码数据,decoder 负责把字节码数据转换成业务数据。

其实 Java 的序列化技术就可以作为 codec 去使用,但是它的硬伤太多:

1. 无法跨语言,这应该是 Java 序列化最致命的问题了。

2. 序列化后的体积太大,是二进制编码的 5 倍多。

3. 序列化性能太低。

由于 Java 序列化技术硬伤太多,因此 Netty 自身提供了一些 codec,如下所示:

Netty 提供的解码器:

1. StringDecoder, 对字符串数据进行解码

2. ObjectDecoder,对 Java 对象进行解码

3. ... ... ...

Netty 提供的编码器:

1. StringEncoder,对字符串数据进行编码

2. ObjectEncoder,对 Java 对象进行编码

3. ... ... ...

Netty 本身自带的 ObjectDecoder 和 ObjectEncoder 可以用来实现 POJO 对象或各种业务

对象的编码和解码,但其内部使用的仍是 Java 序列化技术,所以我们不建议使用。因此对

于 POJO 对象或各种业务对象要实现编码和解码,我们需要更高效更强的技术。

4.6.2 Google 的 Protobuf

Protobuf 是 Google 发布的开源项目,全称 Google Protocol Buffers,特点如下:

l

支持跨平台、多语言(支持目前绝大多数语言,例如 C++、C#、Java、python 等)

l

高性能,高可靠性

l

使用 protobuf 编译器能自动生成代码,Protobuf 是将类的定义使用.proto 文件进行描述, 然后通过 protoc.exe 编译器根据.proto 自动生成.java 文件

目前在使用 Netty 开发时,经常会结合 Protobuf 作为 codec (编解码器)去使用,具体用

法如下所示。

第 1 步:

<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.6.1</version>
</dependency>

上述代码在 pom 文件中分别引入 netty 和 protobuf 的坐标。

第 2 步:假设我们要处理的数据是图书信息,那就需要为此编写 proto 文件

netty教程

第 3 步:通过 protoc.exe 根据描述文件生成 Java 类,具体操作如下所示:

 netty教程

第四步:把生成的 BookMessage.java 拷呗到项目中。这个类我们不要编辑它,直接拿着用即可,该类内部有一个内部类,这个内部类才是真正的 POJO,一定要注意。

第 5 步:在 Netty 中去使用

netty教程

上述代码在编写客户端程序时,要向 Pipeline 链中添加 ProtobufEncoder 编码器对象。

 netty教程

上述代码在往服务器端发送图书(POJO)时就可以使用生成的 BookMessage 类搞定,非常方便。

 netty教程

上述代码在编写服务器端程序时,要向 Pipeline 链中添加 ProtobufDecoder 解码器对象。

 netty教程

上述代码在服务器端接收数据时,直接就可以把数据转换成 POJO 使用,非常方便。

相关推荐