netty 异常处理


netty 异常处理

      

              

                                

相关类与接口

        

ChannelInboundHandler

public interface ChannelInboundHandler extends ChannelHandler {

    void channelRegistered(ChannelHandlerContext var1) throws Exception;
    void channelUnregistered(ChannelHandlerContext var1) throws Exception;

    void channelActive(ChannelHandlerContext var1) throws Exception;
    void channelInactive(ChannelHandlerContext var1) throws Exception;

    void channelRead(ChannelHandlerContext var1, Object var2) throws Exception;
    void channelReadComplete(ChannelHandlerContext var1) throws Exception;

    void userEventTriggered(ChannelHandlerContext var1, Object var2) throws Exception;
    void channelWritabilityChanged(ChannelHandlerContext var1) throws Exception;

    void exceptionCaught(ChannelHandlerContext var1, Throwable var2) throws Exception;
}        //处理inbound事件异常

       

ChannelOutboundHandler

public interface ChannelOutboundHandler extends ChannelHandler {

    void bind(ChannelHandlerContext var1, SocketAddress var2, ChannelPromise var3) throws Exception;
    void connect(ChannelHandlerContext var1, SocketAddress var2, SocketAddress var3, ChannelPromise var4) throws Exception;
    void disconnect(ChannelHandlerContext var1, ChannelPromise var2) throws Exception;

    void close(ChannelHandlerContext var1, ChannelPromise var2) throws Exception;
    void deregister(ChannelHandlerContext var1, ChannelPromise var2) throws Exception;

    void read(ChannelHandlerContext var1) throws Exception;
    void write(ChannelHandlerContext var1, Object var2, ChannelPromise var3) throws Exception;
         //可处理write事件抛出的异常

    void flush(ChannelHandlerContext var1) throws Exception;
}

          

ChannelDuplexHandler:可同时处理inbound、outbound事件异常

public class ChannelDuplexHandler extends ChannelInboundHandlerAdapter implements ChannelOutboundHandler {
    public ChannelDuplexHandler() {
    }

    @Skip
    public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        ctx.bind(localAddress, promise);
    }

    @Skip
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        ctx.connect(remoteAddress, localAddress, promise);
    }

    @Skip
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        ctx.disconnect(promise);
    }

    @Skip
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        ctx.close(promise);
    }

    @Skip
    public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        ctx.deregister(promise);
    }

    @Skip
    public void read(ChannelHandlerContext ctx) throws Exception {
        ctx.read();
    }

    @Skip
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ctx.write(msg, promise);
    }

    @Skip
    public void flush(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}

          

                

                                

使用示例

     

*********

服务端

       

CustomServerInboundHandler

public class CustomServerInboundHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("CustomServerInboundHandler:"+msg);
        ctx.channel().writeAndFlush("服务端返回给客户端的数据");

        //throw new Exception("出错了");
    }
}

          

CustomServerOutboundHandler

public class CustomServerOutboundHandler extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        System.out.println("CustomServerOutboundHandler write:"+msg);
        throw new Exception("服务端返回的信息出错了");
    }
}

             

CustomExceptionHandler

public class CustomExceptionHandler extends ChannelDuplexHandler {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("CustomExceptionHandler inbound异常信息:"+cause.getMessage());
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ctx.write(msg, promise.addListener( future -> {
            if (!future.isSuccess()){
                System.out.println("CustomExceptionHandler outbound异常信息:"+future.cause().getMessage());
            }
        }));
    }
}

          

NettyServer

public class NettyServer {

    public static void startServer(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            channelPipeline.addLast(new StringDecoder());
                            channelPipeline.addLast(new StringEncoder());
                            channelPipeline.addLast(new CustomServerInboundHandler());
                            channelPipeline.addLast(new CustomServerOutboundHandler());
                            channelPipeline.addLast(new CustomExceptionHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        startServer(8000);
    }
}

           

*********

客户端

    

CustomClientHandler

public class CustomClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端开始发送数据");
        ctx.channel().writeAndFlush("客户端向服务端发送数据");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("客户端读取的响应数据:"+msg);
    }
}

       

NettyClient

public class NettyClient {

    public static void connect(String host, int port){
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            channelPipeline.addLast(new StringDecoder());
                            channelPipeline.addLast(new StringEncoder());
                            channelPipeline.addLast("custom",new CustomClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        String host = "localhost";
        int port = 8000;
        connect(host, port);
    }
}

           

*********

使用测试

  

点击运行后,服务端输出:

11:46:40.922 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
11:46:40.922 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.chunkSize: 32
11:46:40.922 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.blocking: false
11:46:40.929 [nioEventLoopGroup-3-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkAccessible: true
11:46:40.929 [nioEventLoopGroup-3-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkBounds: true
11:46:40.930 [nioEventLoopGroup-3-1] DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@4622d7c7
CustomServerInboundHandler:客户端向服务端发送数据
CustomServerOutboundHandler write:服务端返回给客户端的数据
CustomExceptionHandler outbound异常信息:服务端返回的信息出错了

       

点击运行后,客户端输出:

11:46:40.922 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.ratio: 8
11:46:40.922 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.chunkSize: 32
11:46:40.922 [nioEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.blocking: false
11:46:40.929 [nioEventLoopGroup-3-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkAccessible: true
11:46:40.929 [nioEventLoopGroup-3-1] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.checkBounds: true
11:46:40.930 [nioEventLoopGroup-3-1] DEBUG io.netty.util.ResourceLeakDetectorFactory - Loaded default ResourceLeakDetector: io.netty.util.ResourceLeakDetector@4622d7c7
CustomServerInboundHandler:客户端向服务端发送数据
CustomServerOutboundHandler write:服务端返回给客户端的数据
CustomExceptionHandler outbound异常信息:服务端返回的信息出错了

由于服务端有异常,客户端没有接到服务端的响应数据

    

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Netty是一个基于Java的高性能网络编程框架,它提供了一种简单而强大的方式来处理网络通信。在Netty中,异常处理是非常重要的一部分,可以帮助我们及时发现和解决网络通信中的问题。下面是一个Netty异常处理的案例: 1. 异常捕获和处理: 在Netty中,可以通过实现ChannelHandler的exceptionCaught方法来捕获和处理异常。当有异常发生时,Netty会自动调用该方法,并将异常传递给它。在该方法中,我们可以根据具体的异常类型进行相应的处理,例如记录日志、关闭连接等。 ```java public class MyHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 异常处理逻辑 if (cause instanceof IOException) { // 处理IO异常 // ... } else if (cause instanceof IllegalArgumentException) { // 处理参数异常 // ... } else { // 其他异常处理 // ... } // 关闭连接 ctx.close(); } } ``` 2. 异常传播: 在Netty中,异常可以在ChannelPipeline中传播。当一个ChannelHandler抛出异常时,它会被传递给ChannelPipeline中的下一个ChannelHandler,直到被处理或者到达Pipeline的末尾。这种机制可以让我们在不同的Handler中对异常进行处理,从而实现更加灵活的异常处理策略。 3. 异常日志记录: 在Netty中,可以使用日志框架来记录异常信息,以便后续的排查和分析。常用的日志框架有Log4j、Logback等。通过配置日志级别和输出格式,可以将异常信息记录到日志文件中,方便后续的查看和分析。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值