用于从AKKA发送非阻塞http请求的Java示例

它是在AKKA文档中写的

…在一些外部实体(可能是锁,网络套接字等)上,参与者不应该阻塞(即在占用线程时被动等待)。阻塞操作应该在一些特殊的线程中完成,该线程将消息发送给应该对他们采取行动的演员。 来源http://doc.akka.io/docs/akka/2.0/general/actor-systems.html#Actor_Best_Practices

我现在找到了以下信息:

  1. 我读了从Akka / Scala发送出站HTTP请求并检查了https://github.com/dsciamma/fbgl1上的示例

  2. 我发现以下文章http://nurkiewicz.blogspot.de/2012/11/non-blocking-io-discovering-akka.html解释如何使用https://github.com/AsyncHttpClient/async-http-client non blocking http客户端与akka。 但是用Scala编写。

我如何编写一个制作非阻塞http请求的actor?

它必须将远程url页面作为文件,而不是将生成的文件对象发送给主actor。 然后主actor将此请求发送给解析器actor以解析文件…

在最后一个回复中,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() { @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

我已经用这种方式实现了这一点。

 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() { @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); }