用于从AKKA发送非阻塞http请求的Java示例 [英] Java example for sending non-blocking http request from AKKA
问题描述
在AKKA文档中写道
...参与者不应该阻止(即在占用线程时被动等待)外部实体,可能是一个锁,一个网络套接字等。阻塞操作应该在一些特殊的线程中完成,该线程向作者发送消息。
来源 http:// doc.akka.io/docs/akka/2.0/general/actor-systems.html#Actor_Best_Practices
<我现在找到了以下信息:
I have found the following information at the moment :
I发现以下文章 http://nurkiewicz.blogspot.de /2012/11/non-blocking-io-discovering-akka.html 解释如何使用 https://github.com/AsyncHttpClient/async-http-client 非阻止http客户端与akka。但是用Scala编写。
I found following article http://nurkiewicz.blogspot.de/2012/11/non-blocking-io-discovering-akka.html explaining how to use https://github.com/AsyncHttpClient/async-http-client non blocking http client with akka. But is written in Scala.
我如何编写一个制作非阻塞http请求的演员?
How can i write an actor that make non-blocking http requests?
它必须将远程URL页面作为文件,而不是将生成的文件对象发送给主actor。然后主actor将此请求发送给解析器actor以解析文件...
It must downlad a remote url page as file and than send the generated file object to the master actor. master actor then sends this request to parser actor to parse the file...
推荐答案
我已经以这种方式实现了这一点。
I have implemented this in this way.
public class ReduceActor extends UntypedActor {
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof URI) {
URI url = (URI) message;
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.prepareGet(url.toURL().toString()).execute(new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(Response response) throws Exception {
File f = new File("e:/tmp/crawler/" + UUID.randomUUID().toString() + ".html");
// Do something with the Response
// ...
// System.out.println(response1.getStatusLine());
FileOutputStream fao = new FileOutputStream(f);
IOUtils.copy(response.getResponseBodyAsStream(), fao);
System.out.println("File downloaded " + f);
getSender().tell(new WordCount(f));
return response;
}
@Override
public void onThrowable(Throwable t) {
// Something wrong happened.
}
});
} else
unhandled(message);
}
这篇关于用于从AKKA发送非阻塞http请求的Java示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!