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()
,所以我猜这可能有问题。有没有办法将“启动客户端”、“发送请求”、“关闭客户端”分成不同的方法?提前致谢!
最佳答案
最简单的解决方案是使用 netty 提供的 ChannelPool
:https://netty.io/news/2015/05/07/4-0-28-Final.html
它提供开箱即用的 gracefulshutdown
、maxconnections
等。
关于java - Netty Http Client : how to separate client-start,发送请求,和client-shutdown分为不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54716218/