博客
关于我
Netty传输
阅读量:559 次
发布时间:2019-03-09

本文共 3664 字,大约阅读时间需要 12 分钟。

Netty传输API的核心是Channel接口,它用于实现所有的I/O操作

每个Channel都会分配一个ChannelPipeline和ChannelConfig。ChannelConfig包含该Channel的所有配置设置,且支持热更新。由于特定的传输可能需要独特的配置设置,因此它可能会实现ChannelConfig的子接口。

Channel是独一无二的,因此为了保证排序,Channel声明为Comparable接口的子接口。如果两个不同的Channel实例返回相同的散列码,AbstractChannel的compareTo()方法将抛出错误。

ChannelPipeline实现了拦截过滤器模式,持有所有处理入站和出站数据及事件的ChannelHandler。ChannelHandler用于处理状态变化、数据处理以及用户定义事件等。

ChannelHandler的典型功能包括:

  • 数据格式转换
  • 异常通知
  • Channel状态变化通知
  • 注册到EventLoop/注销通知
  • 用户定义事件通知

Channel的核心方法

  • eventLoop:返回分配给Channel的EventLoop
  • pipeline:返回分配给Channel的ChannelPipeline
  • isActive:如果Channel处于活动状态,返回true
  • localAddress、remoteAddress:返回本地和远程的SocketAddress
  • write:将数据写入远端节点
  • flush:将缓冲的数据冲刷到底层传输(如socket)
  • writeAndFlush:简便方法,等同于write()和flush()

内置传输类型

  • NIO(java.nio.channels包):基于选择器的非阻塞I/O
  • Epoll:JNI驱动的epoll,适用于Linux
  • OIO:基于java.net包的阻塞I/O
  • Local:JVM内部通信(不涉及网络流量)
  • Embedded:嵌入式传输,用于ChannelHandler测试

注意事项

  • 零拷贝仅适用于NIO和Epoll传输,用于文件到网络接口快速传输
  • Local传输不支持实体网络流量,客户端需使用同一传输类型-_based传输在同一JVM内通信的完美用例
  • 测试ChannelHandler时使用Embedded传输

应用场景

  • 非阻塞代码库:建议使用NIO或Epoll
  • 阻塞代码库:建议使用OIO
  • JVM内部通信:使用Local传输
  • ChannelHandler测试:使用Embedded传输

示例代码

// 服务器端public class EchoServer {    private final ByteBuf buffer = Unpooled.copiedBuffer("Hello, Yang", Charset.UTF_8);    public void bind(int port) throws Exception {        EventLoopGroup boss = new NioEventLoopGroup();        EventLoopGroup worker = new NioEventLoopGroup();        ServerBootstrap bootstrap = new ServerBootstrap();        try {            bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)                    .childHandler(new ChildChannelHandler());            ChannelFuture future = bootstrap.bind(port).sync();            future.channel().closeFuture().sync();        } finally {            boss.shutdownGracefully();            worker.shutdownGracefully();        }    }    private class ChildChannelHandler extends ChannelInitializer
{ @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; String message = buf.toString(Charset.UTF_8); System.out.println("_received: " + message); ctx.writeAndFlush(buf); } }); } }}

// 客户端

public class EchoClient {    private final ByteBuf buffer = Unpooled.copiedBuffer("Hello, Wang", Charset.UTF_8);    public void connect(int port, String host) throws Exception {        EventLoopGroup group = new NioEventLoopGroup();        try {            Bootstrap bootstrap = new Bootstrap();            bootstrap.group(group).channel(NioSocketChannel.class)                    .option(ChannelOption.TCP_NODELAY, true)                    .handler(new ChildChannelHandler());            ChannelFuture future = bootstrap.connect(host, port).sync();            future.channel().closeFuture().sync();        } finally {            group.shutdownGracefully();        }    }    private class ChildChannelHandler extends ChannelInitializer
{ @Override protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; String message = buf.toString(Charset.UTF_8); System.out.println("_received: " + message); ctx.close(); } }); } }}

参考《Netty实战》

转载地址:http://ghmsz.baihongyu.com/

你可能感兴趣的文章
PHP大文件切片下载代码
查看>>
php如何定义的数位置,php如何实现不借助IDE快速定位行数或者方法定义的文件和位置...
查看>>
RabbitMQ集群 - 普通集群搭建、宕机情况
查看>>
PHP如何读取json数据
查看>>
PHP字符串
查看>>
PHP字符串递增
查看>>
php学习之基础语法
查看>>
RabbitMQ集群 - 仲裁队列、Raft协议(最详细的选举流程)
查看>>
PHP学习总结(11)——PHP入门篇之WAMPServer多站点配置
查看>>
PHP学习总结(12)——PHP入门篇之变量
查看>>
PHP学习总结(13)——PHP入门篇之常量
查看>>
PHP学习总结(14)——PHP入门篇之常用运算符
查看>>
PHP学习总结(1)——PHP入门篇之PHP可以做什么?
查看>>
PHP学习总结(2)——PHP入门篇之PHP代码标识
查看>>
PHP学习总结(4)——PHP入门篇之PHP计算表达式
查看>>
PHP学习总结(5)——PHP入门篇之PHP字符串
查看>>
PHP学习总结(7)——PHP入门篇之PHP注释
查看>>
rabbitmq重启失败
查看>>
PHP学习总结(9)——PHP入门篇之WAMPServer服务控制面板介绍
查看>>
php学习笔记---php调试和开发工具整理
查看>>