gpt4 book ai didi

java非阻塞HTTP客户端

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:25:43 26 4
gpt4 key购买 nike

我有一个大容量的 java 应用程序,我必须在其中将 http 帖子发送到另一台服务器。目前我正在使用 org.apache.commons.httpclient 库:

private static void sendData(String data) {
HttpClient httpclient = new HttpClient();
StringRequestEntity requestEntity;
try {
requestEntity = new StringRequestEntity(data, "application/json", "UTF-8");
String address = "http://<my host>/events/"
PostMethod postMethod = new PostMethod(address);
postMethod.setRequestEntity(requestEntity);

httpclient.executeMethod(postMethod);

} catch (Exception e) {
LOG.error("Failed to send data ", e);

}
}

这意味着我正在同步发送我的 http 请求,这不适合我的多线程高容量应用程序。所以我想将这些调用更改为异步非阻塞 http 调用。

我正在浏览许多选项,例如 apache async clientxsocket但无法使其发挥作用。

已尝试 ning :

private static void sendEventToGrpahiteAsync(String event) {
LOG.info("\n" + "sendEventToGrpahiteAsync");
try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient()) {
BoundRequestBuilder post = asyncHttpClient.preparePost();
post.addHeader("Content-Type", "application/json");
post.setBodyEncoding("UTF-8");
post.setBody(event);
post.execute(new HttpRequestCompletionHandler());
} catch (Exception e) {
LOG.error("Failed to sending event", e);
}
}

我试过 Apache HttpAsyncClient :

private static void sendEventToGrpahiteAsync(String event) {
LOG.info("\n" + "sendEventToGrpahiteAsync");
try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
httpclient.start();
HttpPost request = new HttpPost(addr);
StringEntity entity = new StringEntity(event, ContentType.create("application/json", Consts.UTF_8));
request.setEntity(entity);
httpclient.execute(request, null);
} catch (Exception e) {
LOG.error("Failed to sending event", e);
}
}

我试过了 xsocket :

private static void sendEventToGrpahiteAsync2(String event) {
LOG.info("\n" + "sendEventToGrpahiteAsync");
try (INonBlockingConnection con = new NonBlockingConnection(<SERVER_IP>, 80);
IHttpClientEndpoint httpClientConnection = new HttpClientConnection(con)) {
IHttpResponseHandler responseHandler = new MyResponseHandler();
IHttpRequest request = new PostRequest(url_address, "application/json", Consts.UTF_8.toString(), event);
request.setTransferEncoding(Consts.UTF_8.toString());
httpClientConnection.send(request, responseHandler);
} catch (Exception e) {
LOG.error("Failed to sending event", e);
}
}

我没有发现异常,但帖子也没有到达目标。要清楚,目标是 graphite server所以一旦帖子到达,它就会在图表中清楚地看到。同步帖子运行良好,我可以在图表上看到结果,但我的目标图表上没有显示任何异步帖子。

我错过了什么?

谢谢

最佳答案

明白了。

我使用的所有库都是使用额外的 IO 线程实现的,因此我的进程可能在完全握手之前结束。

一旦我在 http 调用之后添加了 Thread.sleep(2000),一切就都正常了。因此,对于网络应用程序(这是我的情况),我建议的实现很好(但对于 Java 进程,您可能会考虑 NickJ 的回答)。

关于java非阻塞HTTP客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998631/

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