博客
关于我
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/

你可能感兴趣的文章
PostgreSQL 10.1 手册_部分 III. 服务器管理_第 21 章 数据库角色
查看>>
Postgresql 12.9如何配置允许远程连接
查看>>
PostgreSQL 9.6 同步多副本 与 remote_apply事务同步级别 应用场景分析
查看>>
Postgresql CopyManager 流式批量数据入库
查看>>
PostgreSQL cube 插件 - 多维空间对象
查看>>
PostgreSQL Daily Maintenance - cluster table
查看>>
PostgreSQL on Linux 最佳部署手册
查看>>
PostgreSQL Oracle 兼容性之 - pipelined
查看>>
PostgreSQL Point-In-Time Recovery (Incremental Backup)
查看>>
postgresql Streaming Replication监控与注意事项
查看>>
postgresql 不需要付费_使用数据传输在PostgreSQL执行 外部连接运算符
查看>>
postgresql 主从配置_生产环境postgresql主从环境配置
查看>>
postgresql 函数&存储过程 ; 递归查询
查看>>
PostgreSQL 分组聚合查询中 filter 子句替换 case when
查看>>
PostgreSQL 同步流复制锁瓶颈分析
查看>>
PostgreSQL 备份与还原命令 pg_dump
查看>>
Postgresql 外部表插件postgres_fdw的安装和使用
查看>>
PostgreSQL 如何从崩溃状态恢复(上)
查看>>
PostgreSQL 存储过程基本语法
查看>>
PostgreSQL 实现批量更新、删除、插入
查看>>