写在AKKA文档中
...参与者不应该阻塞(即在占用线程时被动等待)某个外部实体,可能是锁,网络套接字等。阻塞操作应该在一些特殊的线程中完成,该线程发送传递给他们的演员的信息。 来源http://doc.akka.io/docs/akka/2.0/general/actor-systems.html#Actor_Best_Practices
我目前找到了以下信息:
我阅读了Sending outbound HTTP request from Akka / Scala,并在https://github.com/dsciamma/fbgl1
我发现以下文章http://nurkiewicz.blogspot.de/2012/11/non-blocking-io-discovering-akka.html解释了如何将https://github.com/AsyncHttpClient/async-http-client非阻止http客户端与akka一起使用。但是用Scala编写。
我怎样才能编写一个制作非阻塞http请求的actor?
它必须将远程URL页面作为文件,而不是将生成的文件对象发送给主actor。然后master actor将此请求发送给解析器actor以解析文件...
答案 0 :(得分:4)
在上一个回复中,Koray对发件人使用了错误的引用,正确的方法是:
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();
final ActorRef sender = getSender();
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);
sender.tell(new WordCount(f));
return response;
}
@Override
public void onThrowable(Throwable t) {
// Something wrong happened.
}
});
} else
unhandled(message);
}
查看akka的另一个帖子:https://stackoverflow.com/a/11899690/575746
答案 1 :(得分:0)
我已经以这种方式实现了这一点。
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);
}