简体   繁体   English

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

[英]Netty Http Client: how to separate client-start, sending request, and client-shutdown into different methods

1. Backgroud 1.背景
I found most of the http client examples using Netty seem to be following this code structure: 我发现使用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();
    }
}

So if I understand it correctly, each time I send a request, I need to create a client, and call client.run() on it. 因此,如果我正确理解它,那么每次发送请求时,都需要创建一个客户端,并在其上调用client.run() That said, it seems I can only make one "fixed" request at a time. 也就是说,似乎我一次只能发出一个“固定”请求。

2.My need 2.我的需要
I need a long-standing client that can send multiple requests. 我需要一个可以发送多个请求的老客户。 More specifically, there will be another thread sending instruction to the client, and each time the client gets the instruction, it will send a request. 更具体地说,将有另一个线程向客户端发送指令,并且每当客户端获得指令时,它将发送一个请求。 Something like this: 像这样:

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.What I've tried 3,我尝试过的
I have tried something like this: 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();        
}

The problem is that it seems this code didn't call workerGroup.shutDownGracefully() , so I'm guessing this can have problems. 问题是似乎此代码未调用workerGroup.shutDownGracefully() ,因此我猜测这可能会有问题。 Is there a way to split the "start client", "send request", "shutdown client" into separate methods? 有没有办法将“启动客户端”,“发送请求”,“关闭客户端”拆分为单独的方法? Thanks in advance! 提前致谢!

The easiest solution will be to use a ChannelPool provided by netty: https://netty.io/news/2015/05/07/4-0-28-Final.html 最简单的解决方案是使用ChannelPool提供的ChannelPoolhttps ://netty.io/news/2015/05/07/4-0-28-Final.html

It provides gracefulshutdown , maxconnections , etc out-of-the-box. 它提供开箱即用的gracefulshutdownmaxconnections等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM