netty(七) Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位。Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码、拦截指定的报文、统一对日志错误进行处理、统一对请求进行计数、控制Handler执行与否。一句话,没有它做不到的只有你想不到的。
Netty中的所有handler都实现自ChannelHandler接口。按照输出输出来分,分为ChannelInboundHandler、ChannelOutboundHandler两大类。ChannelInboundHandler对从客户端发往服务器的报文进行处理,一般用来执行解码、读取客户端数据、进行业务处理等;ChannelOutboundHandler对从服务器发往客户端的报文进行处理,一般用来进行编码、发送报文到客户端。
Netty中,可以注册多个handler。ChannelInboundHandler按照注册的先后顺序执行;ChannelOutboundHandler按照注册的先后顺序逆序执行,如下图所示,按照注册的先后顺序对Handler进行排序,request进入Netty后的执行顺序为:
基本的概念就说到这,下面用一个例子来进行验证。该例子模拟Client与Server间的通讯,Server端注册了2个ChannelInboundHandler、2个ChannelOutboundHandler。当Client连接到Server后,会向Server发送一条消息。Server端通过ChannelInboundHandler 对Client发送的消息进行读取,通过ChannelOutboundHandler向client发送消息。最后Client把接收到的信息打印出来。
Server端一共有5个类:HelloServer InboundHandler1 InboundHandler2 OutboundHandler1 OutboundHandler2
1、HelloServer 代码如下
- package com.guowl.testmultihandler;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- public class HelloServer {
- public void start(int port) 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) throws Exception {
- // 注册两个OutboundHandler,执行顺序为注册顺序的逆序,所以应该是OutboundHandler2 OutboundHandler1
- ch.pipeline().addLast(new OutboundHandler1());
- ch.pipeline().addLast(new OutboundHandler2());
- // 注册两个InboundHandler,执行顺序为注册顺序,所以应该是InboundHandler1 InboundHandler2
- ch.pipeline().addLast(new InboundHandler1());
- ch.pipeline().addLast(new InboundHandler2());
- }
- }).option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true);
- ChannelFuture f = b.bind(port).sync();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- HelloServer server = new HelloServer();
- server.start(8000);
- }
- }
2、InboundHandler1
- package com.guowl.testmultihandler;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class InboundHandler1 extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(InboundHandler1.class);
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- logger.info("InboundHandler1.channelRead: ctx :" + ctx);
- // 通知执行下一个InboundHandler
- ctx.fireChannelRead(msg);
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- logger.info("InboundHandler1.channelReadComplete");
- ctx.flush();
- }
- }
3、InboundHandler2
- package com.guowl.testmultihandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class InboundHandler2 extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(InboundHandler2.class);
- @Override
- // 读取Client发送的信息,并打印出来
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- logger.info("InboundHandler2.channelRead: ctx :" + ctx);
- ByteBuf result = (ByteBuf) msg;
- byte[] result1 = new byte[result.readableBytes()];
- result.readBytes(result1);
- String resultStr = new String(result1);
- System.out.println("Client said:" + resultStr);
- result.release();
- ctx.write(msg);
- }
- @Override
- public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
- logger.info("InboundHandler2.channelReadComplete");
- ctx.flush();
- }
- }
4、OutboundHandler1
- package com.guowl.testmultihandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelOutboundHandlerAdapter;
- import io.netty.channel.ChannelPromise;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class OutboundHandler1 extends ChannelOutboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(OutboundHandler1.class);
- @Override
- // 向client发送消息
- public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
- logger.info("OutboundHandler1.write");
- String response = "I am ok!";
- ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
- encoded.writeBytes(response.getBytes());
- ctx.write(encoded);
- ctx.flush();
- }
- }
5、OutboundHandler2
- package com.guowl.testmultihandler;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelOutboundHandlerAdapter;
- import io.netty.channel.ChannelPromise;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class OutboundHandler2 extends ChannelOutboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(OutboundHandler2.class);
- @Override
- public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
- logger.info("OutboundHandler2.write");
- // 执行下一个OutboundHandler
- super.write(ctx, msg, promise);
- }
- }
Client端有两个类:HelloClient HelloClientIntHandler
1、HelloClient
- package com.guowl.testmultihandler;
- import io.netty.bootstrap.Bootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioSocketChannel;
- public class HelloClient {
- public void connect(String host, int port) throws Exception {
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- Bootstrap b = new Bootstrap();
- b.group(workerGroup);
- b.channel(NioSocketChannel.class);
- b.option(ChannelOption.SO_KEEPALIVE, true);
- b.handler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new HelloClientIntHandler());
- }
- });
- // Start the client.
- ChannelFuture f = b.connect(host, port).sync();
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- HelloClient client = new HelloClient();
- client.connect("127.0.0.1", 8000);
- }
- }
2、HelloClientIntHandler
- package com.guowl.testmultihandler;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class HelloClientIntHandler extends ChannelInboundHandlerAdapter {
- private static Logger logger = LoggerFactory.getLogger(HelloClientIntHandler.class);
- @Override
- // 读取服务端的信息
- public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- logger.info("HelloClientIntHandler.channelRead");
- ByteBuf result = (ByteBuf) msg;
- byte[] result1 = new byte[result.readableBytes()];
- result.readBytes(result1);
- result.release();
- ctx.close();
- System.out.println("Server said:" + new String(result1));
- }
- @Override
- // 当连接建立的时候向服务端发送消息 ,channelActive 事件当连接建立的时候会触发
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- logger.info("HelloClientIntHandler.channelActive");
- String msg = "Are you ok?";
- ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
- encoded.writeBytes(msg.getBytes());
- ctx.write(encoded);
- ctx.flush();
- }
- }
server端执行结果为:
在使用Handler的过程中,需要注意:
1、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。
2、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。
3、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。
netty(七) Handler的执行顺序的更多相关文章
- 7.Netty中 handler 的执行顺序
1.Netty中handler的执行顺序 Handler在Netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截 ...
- hadoop27---netty中handler的执行顺序
Netty是基于Java NIO的网络应用框架. Netty是一个NIO client-server(客户端服务器)框架,使用Netty可以快速开发网络应用,例如服务器和客户端协议.Netty提供了一 ...
- 关于Netty Pipeline中Handler的执行顺序问题
原文地址:http://blog.csdn.net/wgyvip/article/details/25637651 最近在学习Netty框架,根据官网的教程学着做了几个小测试,都成功了,后面开始试着写 ...
- netty4 Handler的执行顺序
转载:https://my.oschina.net/jamaly/blog/272385 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通 ...
- Netty4.0学习笔记系列之二:Handler的执行顺序(转)
http://blog.csdn.net/u013252773/article/details/21195593 Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet ...
- Netty4.0学习笔记系列之二:Handler的执行顺序
Handler在netty中,无疑占据着非常重要的地位.Handler与Servlet中的filter很像,通过Handler可以完成通讯报文的解码编码.拦截指定的报文.统一对日志错误进行处理.统一对 ...
- Netty学习:ChannelHandler执行顺序详解,附源码分析
近日学习Netty,在看书和实践的时候对于书上只言片语的那些话不是十分懂,导致尝试写例子的时候遭遇各种不顺,比如decoder和encoder还有HttpObjectAggregator的添加顺序,研 ...
- MySQL逻辑架构、SQL加载执行顺序、七种JOIN模式图解
逻辑架构 存储引擎 查看当前安装的mysql提供的存储引擎 查看当前mysql默认的存储引擎 MyISAM和InnoDB SQL加载执行顺序 sql书写顺序 mysql解析器执行的顺序 考点:m ...
- netty中Pipeline的ChannelHandler执行顺序案例详解
一.netty的Pipeline模型 netty的Pipeline模型用的是责任链设计模式,当boss线程监控到绑定端口上有accept事件,此时会为该socket连接实例化Pipeline,并将In ...
随机推荐
- Ubuntu16.04下安装Hyperledger Fabric 1.0.0
系统环境 * Ubuntu: 16.04 * Go: 1.9.2 * NodeJS: v6.12.0 * Docker: 17.09.0-ce * HyperLedger Fabric: 1.0.0 ...
- Python【每日一问】07
问:请解释使用 *args 和 **kwargs 的含义 答: *args:可变参数,表示将实参中按照位置传值,多余的值都给 args,多余的实参被打包成 tuple(元组),然后传递给函数调用 # ...
- Listen and Write 18th Feb 2019
Weighted blanket has becomes very popular in many homes. they claim it can provide better sleep and ...
- 02_编写Table的CRUD
1.使用EF的Code First模式生成DbContext和表对应的实体类 2.编写CRUD接口: 3.集成Swagger接口生成工具,方便测试使用: https://www.cnblogs.com ...
- 音乐出身的妹纸,零基础学习JAVA靠谱么
问:表示音乐出身的妹纸一枚 某一天突然觉得身边认识的是一群程序员 突然想 要不要也去试试... 众好友都觉得我该去做个老师,可是我怕我会误人子弟,祸害祖国下一代..... 要不要 要不要 学Ja ...
- 02 jmeter性能测试系列_JForum测试论坛的环境搭建
软件测试高端专家培训 QQ 讨论群498721021 网站http://www.szwpinfo.com 1.进入jforum的官方网站,地址http://jforum.net/,下载 2.放入到to ...
- MyBatis注解-动态SQL 一个 SqlProvider的demo
Provider动态语言注解 MyBatis提供了多个注解如:@InsertProvider,@UpdateProvider,@DeleteProvider和@SelectProvider,这些都是建 ...
- Javascript面向对象编程(一)
什么是面向对象? 它是一种新的编程模式.以往的面向过程是将功能都写在一起,逐行实现.面向对象与其不同,它只关心对象提供的功能,而不在乎细节. 面向对象的特点? 抽象:抓住问题的核心,贯穿始终: 封装: ...
- LeetCode 141. Linked List Cycle 判断链表是否有环 C++/Java
Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked lis ...
- BATCH、事务、CLOB、BLOB
Batch:需要执行大量的数据时可以使用批处理 注意点: 1.尽量使用Statement,因为如果是PreParedStatement可能会因为数据量太大而存在空间问题,编译器会报错. 2.把自动提交 ...