[英]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.