![](/img/trans.png)
[英]How does a http client associate an http response with a request (with Netty) or in general?
[英]How to call properly HTTP client from HTTP server request handler in netty?
我正在使用 .netty 3.3.1 開發自定義 HTTP 服務器。
我需要實現這樣的東西
這意味着客戶端請求 (2) 必須表現為同步。
我寫的是基於HttpSnoopClient 示例,但它不起作用,因為我收到
java.lang.IllegalStateException:
await*() in I/O thread causes a dead lock or sudden performance drop. Use addListener() instead or call await*() from a different thread.
我重構了上面提到的示例中的代碼,現在它看起來不像這樣(從 HttpSnoopClient 的第 7f 行開始):
ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
future.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
System.err.println("Cannot connect");
future.getCause().printStackTrace();
bootstrap.releaseExternalResources();
return;
}
System.err.println("Connected");
Channel channel = future.getChannel();
// Send the HTTP request.
channel.write(request);
channel.close();
// Wait for the server to close the connection.
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
System.err.println("Disconnected");
bootstrap.releaseExternalResources(); // DOES NOT WORK?
}
});
}
});
}
}
上例中的run()
命令在我的 herver 處理程序的messageReceived
function 中被調用。
所以它變成了異步的並且避免了 await* 函數。 正確調用請求。 但是-出於我不知道的原因-這條線
bootstrap.releaseExternalResources(); // DOES NOT WORK?
不起作用。 它拋出一個異常,說我無法終止我當前正在使用的線程(這聽起來很合理,但仍然沒有給我一個如何以不同方式做到這一點的答案)。
我也不確定這是正確的方法嗎?
也許你可以在.netty 中推薦一個此類事件編程技術的教程? 通常如何處理一些必須按指定順序調用並相互等待的異步請求?
謝謝,
如果你真的想在關閉時釋放引導程序,你可以這樣做:
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
System.err.println("Disconnected");
new Thread(new Runnable() {
public void run() {
bootstrap.releaseExternalResources();
}
}).start();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.