netty 4.0.13 使用样例

本文介绍了一个基于Netty的客户端实现方案,该客户端能够与服务器进行有效的数据交互。客户端通过设置NioEventLoopGroup并配置Bootstrap初始化参数来建立连接,并使用LengthFieldBasedFrameDecoder等组件处理数据帧。此外,还实现了NettyClientCSHandler类来处理来自服务器的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public boolean connect(final int port ,final String host, final NettyEntity entity) throws Exception {
   Thread.sleep(5000);
   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
         protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("frameDecoder",new LengthFieldBasedFrameDecoder(1024*1024, 0,4, 0, 4));
            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
            pipeline.addLast("decoder",new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
            pipeline.addLast("encoder",new ObjectEncoder());
            pipeline.addLast("handler", new NettyClientCSHandler());
         };

      });
      try {
         byte[] entityBytes = CompressUtil.compress(JSON.toJSONString(entity).getBytes());
         ChannelFuture  f = b.connect(host, port).sync();
         f.channel().writeAndFlush(entityBytes);
         f.channel().closeFuture().sync();
         logger.info("执行JOB端:发送JOB到Server("+host+":"+port+")写数据完成,数据包大小:"+entityBytes.length );
         return true;
      }catch (Exception e){

         logger.error("monitor error , 连接Server失败"+ host+":"+port+"{}");
         return false;
      }
   } finally {
      workerGroup.shutdownGracefully();
   }
}

public class NettyClientCSHandler extends ChannelInboundHandlerAdapter  {
   private static final Logger logger = LoggerFactory.getLogger(NettyClientCSHandler.class);
   public NettyClientCSHandler(){
   }

   /**
    *  NETTY 通信 CLIENT TO SERVER 回调接收
    * @param ctx
    * @param msg
    * @throws Exception
    */
   @Override
   public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      try {
         String result = new String(CompressUtil.uncompress((byte[]) msg));
         if(!StringUtils.isEmpty(result)) {
            Map backData = JSONUtil.jsonToMap(result);
            if (backData != null) {

               logger.error("✔  ****** Client接收到Server回调SUCCESS成功,DB数据处理成功 ******");
            }
         }else{
            logger.error("✘  ****** Client接收到Server回调ERROR失败 ****:" + result);
         }
      }catch (Exception e){
         logger.error("✘  ****** NETTY 通信 CLIENT TO SERVER 回调接收 ERROR失败 ****:",e);
      }finally {
         ctx.close();
      }
   }

   @Override
   public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
      logger.error("****** Netty Client报错 ******",cause.getMessage());
   }






### Netty 实现零拷贝示代码 在Netty中,`Unpooled`类提供了便捷的方法来创建`CompositeByteBuf`实而不涉及额外的内存复制操作[^1]。下面是一个简单的子展示如何利用这些特性实现所谓的“零拷贝”,即减少不必要的数据传输过程中的副本创建。 ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.Unpooled; public class ZeroCopyExample { public static void main(String[] args) { // 创建两个独立的 ByteBuf 对象 ByteBuf buffer1 = Unpooled.copiedBuffer("Hello".getBytes()); ByteBuf buffer2 = Unpooled.copiedBuffer("World!".getBytes()); try (// 使用 CompositeByteBuf 来组合多个 ByteBuf 而不发生实际的数据复制 CompositeByteBuf compositeBuffer = Unpooled.compositeBuffer()) { // 将各个 Buffer 添加到复合缓冲区中 compositeBuffer.addComponent(true, buffer1); compositeBuffer.addComponent(true, buffer2); // 输出最终的结果字符串 System.out.println(compositeBuffer.toString(io.netty.util.CharsetUtil.UTF_8)); } finally { // 释放资源 if (buffer1 != null) buffer1.release(); if (buffer2 != null) buffer2.release(); } } } ``` 此段程序展示了通过`Unpooled`工具类快速构建`CompositeByteBuf`对象的方式,在这个过程中并没有执行真正的字节级别的复制动作,从而实现了高效的数据处理机制。此外,“零拷贝”的概念还涉及到操作系统层面的操作,比如避免用户空间与内核空间之间的频繁切换所带来的性能损耗等问题[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值