gpt4 book ai didi

java - Netty Http Client : how to separate client-start,发送请求,和client-shutdown分为不同的方法

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:21:58 28 4
gpt4 key购买 nike

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

它提供开箱即用的 gracefulshutdownmaxconnections 等。

关于java - Netty Http Client : how to separate client-start,发送请求,和client-shutdown分为不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54716218/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com