Netty Http客户端:如何将客户端启动,发送请求和客户端关闭分为不同的方法

时间:2019-02-15 19:55:30

标签: java http netty

1。背景
我发现使用Netty的大多数http客户端示例似乎都遵循以下代码结构:

public void run() {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();
        // send something
        ch.writeAndFlush(XXXX);
        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

因此,如果我理解正确,则每次发送请求时,都需要创建一个客户端,并在其上调用client.run()。也就是说,似乎我一次只能发出一个“固定”请求。

2。我的需要
我需要一个可以发送多个请求的老客户。更具体地说,将有另一个线程向客户端发送指令,并且每当客户端获得指令时,它将发送一个请求。像这样:

Client client = new Client();
client.start();

client.sendRequest(request1);
client.sendRequest(request2);
...
client.shutDownGracefully(); // not sure if this shutdown is necessary or not
// because I need a long-standing client to wait for instructions to send requests
// in this sense it's kinda like a server.

3。我尝试过的事情
我已经尝试过类似的操作:from this link

public MyClient(String host, int port) {
    System.out.println("Initializing client and connecting to server..");
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();
    b.group(workerGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.SO_KEEPALIVE, true)
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast(new StringDecoder());
                channel.pipeline().addLast(new StringEncoder());
                channel.pipeline().addLast(new MyAppClientHandler());
            }
        });

    channelFuture = b.connect(host, port);
}

public ResponseFuture send(final String msg) {
    final ResponseFuture responseFuture = new ResponseFuture();

    channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(ChannelFuture future)
                throws Exception {
            channelFuture.channel().pipeline().get(MyAppClientHandler.class).setResponseFuture(responseFuture);
            channelFuture.channel().writeAndFlush(msg);                             
        }
    });

    return responseFuture;
}

public void close() {
    channelFuture.channel().close();        
}

问题是似乎此代码未调用workerGroup.shutDownGracefully(),因此我猜测这可能会有问题。有没有办法将“启动客户端”,“发送请求”,“关闭客户端”拆分为单独的方法?预先感谢!

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是使用netty提供的https://netty.io/news/2015/05/07/4-0-28-Final.html

它提供了现成的ChannelPoolgracefulshutdown等。