所有,
我正在尝试决定是否将NodeJS或Java用于我的应用程序.我将通过HTTP与CouchDB进行通信,并希望采用异步非阻塞设计,我的应用程序线程可以在等待来自CouchDB的查询响应时处理其他请求.
我更喜欢使用Java,我一直在寻找AsyncHttpClient作为潜在的解决方案.但是,我在理解图书馆方面遇到了一些麻烦,并认为我可能对某些内容存在根本性的误解.
我在这里发布了一个要点:https://gist.github.com/conorgil/5505603
我希望这个要点打印出"请求X发送!" 并为每个请求"响应X:某事".但是,在每个Future调用get()之前,似乎没有进行HTTP调用(因此,处理程序没有执行).取消注释第23行f.get()会使代码按预期工作,但是对Future#get()的调用是阻塞的,对吗?有没有办法只提供一个回调函数,一旦HTTP响应被完全检索而没有阻塞就会被执行?
类似于以下内容:1)请求进入主线程2)异步,非阻塞HTTP调用CouchDB.注册完成处理程序以处理来自CouchDB的响应3)主线程现在可以自由处理下一个请求4)来自CouchDB的HTTP响应到达某个点并且调用注册的处理程序来执行某些业务逻辑5)主线程继续只处理请求(对于不需要访问CouchDB的请求,可以非常快速地响应它们)
我从根本上误解了一些事情吗?是否可以在Java中执行此类操作?是AsyncHttpClient的答案吗?这个问题是相关的,但不确定自2011年以来情况是否发生了变化(使用Java AsyncHttpClient库执行异步连接?)
由于NodeJS运行事件循环,因此这种非阻塞的异步行为是标准的.您只需注册一个回调函数来处理收到的DB响应,并且事件循环在此期间只处理其他事情.
任何和所有的建议表示赞赏.
谢谢,康纳
出于项目目的,我必须坚持使用Java 1.6进行开发,我使用了异步客户端jar文件并将其合并到我的项目中以实现异步功能,并使用java 1.6开发并导出了JAR。这个jar包含在java 7上运行的另一个Web项目的构建路径中。它在java 7 64位和tomcat7 64位上运行良好。但是当使用java 7 32位和tomcat7 32位时看到以下错误:
java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/apache/catalina/loader/WebappClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of org/apache/catalina/loader/StandardClassLoader) for resolved class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type taticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory; used in the signature
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:299)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:269)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:281)
at com.ning.http.client.AsyncHttpClient.<clinit>(AsyncHttpClient.java:146)
at com.netspective.ems.invoker.AsyncApiInvoker.post(AsyncApiInvoker.java:39)
at com.netspective.ems.invoker.AsyncApiInvoker.post(AsyncApiInvoker.java:32)
at com.netspective.ems.invoker.AsyncApiInvoker.post(AsyncApiInvoker.java:73)
at com.netspective.ems.api.ExceptionApi.notify(ExceptionApi.java:42)
at com.netspective.ems.NetspectiveEMS.prepareAndPostDetails(NetspectiveEMS.java:101)
at com.netspective.ems.NetspectiveEMS.log(NetspectiveEMS.java:168)
at com.netspective.watchtower.sdk.log4j.WatchtowerClientAppender.append(WatchtowerClientAppender.java:32)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
at org.apache.log4j.Category.callAppenders(Category.java:206) …Run Code Online (Sandbox Code Playgroud) 我不知道如何使用HttpClient POST JSON.我找到了一些解决方案,像这样,但我必须使用HttpClient,导致异步并且必须添加标头.
这是我的代码.知道怎么解决吗?
List<Order> list = new List<Order> { new Order() { Name = "CreatedTime", OrderBy = 1 } };
Queues items = new Queues { Orders = list };
var values = new Dictionary<string, string> { { "Orders", JsonConvert.SerializeObject(list) } };
var content = new FormUrlEncodedContent(values);
//HttpContent cc = new StringContent(JsonConvert.SerializeObject(items));
_msg = await _client.PostAsync(input, content);
//_msg = await _client.PostAsync(input, cc);
var response = await _msg.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud) 我正在AsyncHttpClient从命令行程序使用 ning。我需要等待所有请求结束,以便我可以安全地调用close()客户端。挑战在于我从该计划的许多不同部分提出了许多请求。onCompleted下面剥离了自己的代码,显示了我从另一个请求执行嵌套 HTTP 请求的场景:
final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Future<Response> f1 = asyncHttpClient.prepareGet(url).execute(
new AsyncCompletionHandler<Response>() {
public Response onCompleted(Response response)
throws Exception {
//Make more HTTP calls
Future f2 = asyncHttpClient.prepareGet(url).execute(...);
return response;
}
});
Run Code Online (Sandbox Code Playgroud)
这只是示例代码。真实的代码更加复杂并且有更多的 HTTP 调用。close()在我呼叫客户之前确保所有呼叫都已完成的最佳方法是什么?
我正在寻找一个Scala WebSocket客户端。有许多示例,要点和手工艺品,但其中大多数不起作用(不再使用了吗?),而且似乎都没有得到维护。围绕AsyncHttpClient的Scala包装器会很好。感谢您的指导!
经过一些基准测试后,我发现 AsyncHttpClient ( https://github.com/AsyncHttpClient/async-http-client ) 似乎是最稳定和可扩展的异步 http 客户端,因为它基于 NIO 并且似乎可以很好地扩展加载期间。我将它与 OkHttp 和 Apache Async 进行了比较,在模拟具有延迟的后端时,它似乎表现得非常好。
不幸的是,我还没有找到任何方法将其公开为 Spring AsyncRestTemplate,这使得在我们现有的代码库中进行迁移变得很痛苦。
有谁知道使用该库与 RestTemplate 的任何良好桥梁,或者如果不是的话,如何在 Spring 项目中创建一个问题以将其包含在其他异步 http 客户端工厂中?
我正在使用com.loopj.android:android-async-http:1.4.9我的服务器请求。在我的服务器中要求我使用SSL / TLS之前,它一直运行良好。因此,我需要修改AsyncHTTPClient以在所有URL中使用HTTPS。
我检查了类似的方法,如何使用AsyncHttpClient进行HTTPS调用?但没有提供明确的解决方案。由于库本身发出以下警告,因此可接受的解决方案也不安全:
警告!这会忽略每台设备上的SSL证书验证,请谨慎使用。
所以我继续检查其他解决方案。我最终遵循了以下建议:https : //developer.android.com/training/articles/security-ssl.html。因此,我有类似的东西:
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", …Run Code Online (Sandbox Code Playgroud) 我有一个如下所示的卷曲请求:
curl -i -XPOST 'http://my_url:port/write?db=myDb' -u user:xxxxx --data-binary 'FieldName,host=M.233 value=52.666 timestamp'
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 HttpClient 发布此请求。我不确定应该如何称呼它。这就是我试图做的:
public async void TestHttpClient()
{
var client = new HttpClient();
var credentials = Encoding.ASCII.GetBytes("user:xxxxx");
var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
client.DefaultRequestHeaders.Authorization = header;
client.BaseAddress = new Uri("http://my_url:port/write?db=myDb");
var result = await client.PostAsync(..);
}
Run Code Online (Sandbox Code Playgroud)
我应该为 PostAsync() 编写哪些参数?
如何从curl 转换--data-binary为FieldName,host=M.233 value=52.666 timestampHttpClient?
我正在调用一个具有巨大正文(html)的电子邮件营销服务。主体大小 = 117184。
我正在使用 AsyncHttpClient,它使用 Netty 作为背景。
当我直接调用请求时,它是成功的,但当我尝试使用内部 https 代理服务器时,它会失败并出现以下异常。但是带有代理服务器的小型机构可以正常工作。以下是斯卡拉代码:
val client = asyncHttpClient(config().setProxyServer(proxyServer("XX-XYXY-100X.XXXX.local", 8080)))
val whenResponse = client.preparePost("https://api.sendgrid.com/v3/mail/send")
.addHeader("Authorization", "Bearer XXXXXXXXX")
.addHeader("Content-Type", "application/json")
.setBody(randomBody)
.execute
.get(1000, TimeUnit.SECONDS)
Run Code Online (Sandbox Code Playgroud)
基本上 :
对于使用代理服务器的大型请求,我看到以下异常。
Exception in thread "main" java.util.concurrent.ExecutionException: javax.net.ssl.SSLException: handshake timed out
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1915)
at org.asynchttpclient.netty.NettyResponseFuture.get(NettyResponseFuture.java:207)
at send.RequestSender$.send1(RequestSender.scala:27)
at send.RequestSender$.delayedEndpoint$send$RequestSender$1(RequestSender.scala:47)
at send.RequestSender$delayedInit$body.apply(RequestSender.scala:14)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:389)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at send.RequestSender$.main(RequestSender.scala:14)
at send.RequestSender.main(RequestSender.scala)
Caused by: javax.net.ssl.SSLException: handshake timed out
at …Run Code Online (Sandbox Code Playgroud) 我试图理解Java 8中的CompletableFuture.作为其中的一部分,我正在尝试进行一些REST调用以巩固我的理解.我正在使用这个库来进行REST调用:https://github.com/AsyncHttpClient/async-http-client.
请注意,此库返回GET调用的Response对象.
以下是我要做的事情:
构建UserPost对象的集合,每个对象都有一个用户对象和用户发布的帖子列表.
public class UserPosts {
private final User user;
private final List<Post> posts;
public UserPosts(User user, List<Post> posts) {
this.user = user;
this.posts = posts;
}
@Override
public String toString() {
return "user = " + this.user + " \n" + "post = " + posts+ " \n \n";
}
Run Code Online (Sandbox Code Playgroud)
}
我目前实现如下:
package com.CompletableFuture;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture; …Run Code Online (Sandbox Code Playgroud) asynchttpclient ×10
java ×5
c# ×2
netty ×2
.net ×1
android ×1
curl ×1
java-8 ×1
json ×1
linkageerror ×1
ning ×1
scala ×1
sendgrid ×1
spring ×1
spring-boot ×1
spring-mvc ×1
ssl ×1
tls1.2 ×1
tomcat ×1
websocket ×1