Java example for sending non-blocking http request from AKKA

The AKKA documentation says that

... Actors should not block (i.e. passively wait while occupying Thread) on some external object, which may be a lock, a network socket, etc. Blocking operations must be performed in some special streamlined stream that sends messages to actors who will act on them. source http://doc.akka.io/docs/akka/2.0/general/actor-systems.html#Actor_Best_Practices

At the moment, I have found the following information:

How can I write an actor who makes non-blocking HTTP requests?

He should omit the remote URL page as a file and send the sent file file to the main actor. the master actor then sends this request to the parser to parse the file ...

+4
source share
2 answers

I implemented it 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); } 
0
source

In the last answer, Korea uses the wrong link for the sender, the correct way to do this is:

 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); } 

Checkout this second branch akka: fooobar.com/questions/1444868 / ...

+4
source

Source: https://habr.com/ru/post/1444866/


All Articles