[英]Netty Http Client: how to separate client-start, sending request, and client-shutdown into different methods
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,我尝试过的
我已经尝试过这样的事情: 通过此链接
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()
,因此我猜测这可能会有问题。 有没有办法将“启动客户端”,“发送请求”,“关闭客户端”拆分为单独的方法? 提前致谢!
最简单的解决方案是使用ChannelPool
提供的ChannelPool
: https ://netty.io/news/2015/05/07/4-0-28-Final.html
它提供开箱即用的gracefulshutdown
, maxconnections
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.