【问题标题】:Shutting down Netty server itself关闭 Netty 服务器本身
【发布时间】:2019-08-14 18:18:40
【问题描述】:

我正在使用 Netty 服务器来解决这个问题:逐行读取一个大文件并对其进行处理。在单机上执行它仍然很慢,所以我决定使用服务器向客户端提供大块数据。这已经有效,但我还想要的是服务器在处理整个文件时自行关闭。我现在使用的源代码是:

public static void main(String[] args) {
    new Thread(() -> {
        //reading the big file and populating 'dq' - data queue
    }).start();

    final EventLoopGroup bGrp = new NioEventLoopGroup(1);
    final EventLoopGroup wGrp = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new StringDecoder());
                        p.addLast(new StringEncoder());
                        p.addLast(new ServerHandler(dq, bGrp, wGrp));
                    }
                });
        ChannelFuture f = b.bind(PORT).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

class ServerHandler extends ChannelInboundHandlerAdapter {
    public ServerHandler(dq, bGrp, wGrp) {
        //assigning params to instance fields
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //creating bulk of data from 'dq' and sending to client
        /* e.g.
        ctx.write(dq.get());
         */
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        if (dq.isEmpty() /*or other check that file was processed*/ ) {
            try {
                ctx.channel().closeFuture().sync();
            } catch (InterruptedException ie) {
                //...
            }
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
        ctx.executor().parent().shutdownGracefully();
    }
}

channelReadComplete(...) 方法中的服务器关闭是否正确?我担心的是仍然可以有另一个服务的客户(例如,在其他客户中发送大批量并且当前客户到达'dq'的末尾)。

基本代码来自 netty EchoServer/DiscardServer 示例。

问题是:当达到特定条件时如何关闭netty服务器(从处理程序)。

谢谢

【问题讨论】:

    标签: java netty


    【解决方案1】:

    您不能通过处理程序关闭服务器。您可以做的是向另一个线程发出信号,告知它应该关闭服务器。

    【讨论】:

    • 我已经搜索过,但没有找到解决方案。你能发布一个代码sn-p吗?应该完全分离线程还是在netty中注册的东西?谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2015-04-07
    • 2014-07-17
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多