Question

Reading the Scala doc I am having difficulty understanding the difference between ask and tell.

http://doc.akka.io/docs/akka/snapshot/scala/actors.html states :

! means “fire-and-forget”, e.g. send a message asynchronously and return immediately. Also known as tell.

? sends a message asynchronously and returns a Future representing a possible reply. Also known as ask.

If the actor I'm using spawns a web request then what is the difference between ask and tell ? In both cases the request will be spawned asynchronously and must wait for a response, in other words how can "tell" return immediately if the actor is invoking a web service and awaiting a response ?

Était-ce utile?

La solution 2

It sounds like you already know the basic difference between ask and tell, but don't understand how tell could be used to involve other actors in handling HTTP requests.

In order for it to make sense to use tell in your HTTP request handlers, you have to use an HTTP server that does not require that request handlers return their responses. Spray is such an HTTP server.

In Spray a request handler does not return its response; it is given a RequestContext object, and responding to the request involves invoking some method on it. You can simply send that RequestContext to another actor, which can then respond to the request:

path("foo") {
  rc => rc complete "foo"  // respond here
} ~
path("bar") {
  rc => barActor ! DoBar(rc)  // send it to bar; NO RESPONSE HERE
}

Then the actor referred to by barActor could say

case DoBar(rc) =>
  rc complete "bar"  // respond here, in another actor

The fact that Spray packages up the request context into an object that can be passed around and completed from any actor is a great fit for the actor model. If, on the other hand, your web framework requires that the invoked handler return the response, then if you want to involve another actor your only choice is to use ask.

Typesafe announced that Play will soon use Spray underneath. I hope that means that Play will then allow requests to be sent along to other actors for processing.

Autres conseils

The difference between ask and tell is from the point of view of the message sender (which is not necessarily an actor). ask will send the message and return a future, which can be awaited until timeout or a reply is received, tell will send the message and return immediately.

In the case of ask, the actor that receives the message should reply to the sender when the operation is completed.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top