I have the following code inside an Actor
def receive = {
case All() => {
val collection: BSONCollection = db("ping")
val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
val zender = sender
future onComplete {
case Success(list) => zender ! list
case Failure(throwable) => zender ! List()
}
}
}
I don't like how I have to use the onComplete function to send the result back to the sender actor. I'd like to know if it is possible to convert it into something like this:
def receive = {
case All() => {
val collection: BSONCollection = db("ping")
val future:Future[List[Ping]] = collection.find(BSONDocument()).cursor[Ping].toList()
"sender ! future" // one option
"future.map( list => sender ! list)" //Another option. I know it's not map, but maybe another function
}
}
I feel that this flows better with future chaining.
You can use the pipe pattern for that. Just import akka.pattern.pipe and then you'll be able to pipe messages from futures to actors with future pipeTo actor.
If you want to have an empty list when failure happens, you probably want to have chained calls of "recover" and "pipeTo".
Related
I've built an Akka actor that queries an API at regular intervals, like this:
val cancellable =
system.scheduler.schedule(0 milliseconds,
5 seconds,
actor,
QueryController(1))
The Actor, in essence is:
object UpdateStatistics {
/**
* Query the controller for the given switch Id
*
* #param dpId Switch's Id
*/
case class QueryController(dpId: Int)
case object Stop
def props: Props = Props[UpdateStatistics]
}
class UpdateStatistics extends Actor with akka.actor.ActorLogging {
import UpdateStatistics._
def receive = {
case QueryController(id) =>
import context.dispatcher
log.info(s"Receiving request to query controller")
Future { FlowCollector.getSwitchFlows(1) } onComplete {
f => self ! f.get
}
case Stop =>
log.info(s"Shuting down")
context stop self
case json: JValue =>
log.info("Getting json response, computing features...")
val features = FeatureExtractor.getFeatures(json)
log.debug(s"Features: $features")
sender ! features
case x =>
log.warning("Received unknown message: {}", x)
}
}
What I am trying to do is get the json:Jvalue message out of UpdateStatistics actor. Reading the Akka docs I thought this may be useful:
implicit val i = inbox()
i.select() {
case x => println(s"Valor Devuelto $x")
}
println(i receive(2.second))
But I do not know how to modify UpdateStatistics actor in order to send the result to the inbox above.
Another option I've read in the docs are event streams.
But I do not think this is the correct way.
Is there a way of achieving what I want to do? Or do I need to use a second Actor to which I send the JSON response?
You probably are looking for the ask pattern in AKKA. This will allow you to return a value to the sender.
import akka.pattern.ask
import akka.util.duration._
implicit val timeout = Timeout(5 seconds)
val future = actor ? QueryController(1)
val result = Await.result(future, timeout.duration).asInstanceOf[JValue]
println(result)
To make this work, you need to send the response to the original sender, rather than self. Also, you should beware the dangers of closing over sender in a future when handling messages.
ActorSelection support wildcard and it allows to send a message to all actors that match the selection:
context.actorSelection("../*") ! msg
Is there a way to retrieve the list of ActorRef that match the selection from the ActorSelection?
From the documentation I can see that there is a resolveOne function but not (for example) a resolveList.
Update
The reason why I want the list of ActorRef is that I would like to use the ask operator on all the actors that match the selection.
Just to be clear here is an example of what I would like to do:
object MyActor {
case object AskAllActors
case object GetActorInfo
}
class MyActor extends Actor {
import MyActor._
def receive = {
case AskAllActors =>
val actors: List[ActorRef] = context.actorSelection("../*").resolveList()
val result: List[Future[String]] = actors.map { a => (a ? GetActorInfo).mapTo[String] }
Future.sequence(result).map { result =>
// do something with result: List[String]
}
}
}
The ability to get a list of the form
val timeout : FiniteDuration = 10 seconds
val actorList = actorSelection.resolveMany(timeout)
does not exist. I suspect the reason is because once the timeout expires there is a chance that an Iterable, of non-zero length, is returned but it would be impossible to know if the Iterable is comprehensive. Some Actors may not have had enough time to respond. With resolveOne the issue does not exist, the first responding ActorRef is the result.
Based on the documentation it looks like you could use the Identify message to have all of the Actors specified in an actorSelection respond with identification:
class Follower extends Actor {
val identifyId = 1
context.actorSelection("../*") ! Identify(identifyId)
def receive = {
case ActorIdentity(`identifyId`, Some(ref)) => ...
}
}
A future from the main method of a program sends a msg to its actor asking for an iterable object. The actor then creates another future that asks for the iterable object (say an ArrayBuffer) from a remote actor. After receiving the ArrayBuffer from the remote actor, how would the actor send it back to the first future in the main method? It seems creating a local alias of sender and creating a separate case class to represent the iterable does not prevent dead letters from being encountered.
Here is a sample code:
case class SequenceObject(sqnce:Seq[someArrayBuffer])
//...
implicit val timeout = Timeout(10 seconds)
val fut1: Future[Any] = myActor ? iNeedAnArrayBufferObject
fut1.onSuccess {
case listOfItems: SequenceObject => {
//do sth with listofItems.sqnce
}
class myActor extends Actor {
implicit val timeout = Timeout(1 seconds)
def receive = {
case a: iNeedAnArrayBufferObject => {
val originalSender = sender
val fut: Future[Any] = (remoteActor ? a)
fut.onSuccess {
case list: SequenceObject => {
originalSender ! SequenceObject(list.sqnce)
}
}
The remote actor code is:
class ServerActorClass extends Actor {
def receive = {
case a: iNeedAnArrayBufferObject => {
val closer = sender()
closer ! SequenceObject(ArrayBufferObject[information])
}
}
The above does not seem to work. The remote actor and the local actor can communicate and messages are received correctly. However, the iterable object is never send back to fut1. Why is that? Thanks in advance.
Check pipeTo pattern in Ask: Send-And-Receive-Future section
I have an Akka actor responsible of handling http calls. I use scala dispatch to send multiple HTTP requests over an API:
urls.foreach { u
val service = url(u)
val promise = Http(service OK as.String).either
for(p <- promise)
{
p match
{
case Left(error) =>
faultHandler(error)
case Right(result) =>
resultHandler(result)
}
}
In the resultHandlerfunction, I increment an instance variable nbOfResults and compare to the number of calls I have done.
def resultHandler(result:String)
{
this.nbOfResults++
...
if(nbOfResults == nbOfCalls)
// Do something
}
Is it safe ? May the nbOfResultsvaraible be accessed at the same time if two calls return their results simultaneously ?
For now, I believed that the actor is more or less equivalent to a thread and therefore the callback functions are not executed concurrently. Is it correct ?
Here is a variant of Alexey Romanov response using only dispatch :
//Promises will be of type Array[Promise[Either[Throwable, String]]]
val promises = urls.map { u =>
val service = url(u)
Http(service OK as.String).either
}
//Http.promise.all transform an Iterable[Promise[A]] into Promise[Iterable[A]]
//So listPromise is now of type Promise[Array[Either[Throwable, String]]]
val listPromise = Http.promise.all(promises)
for (results <- listPromise) {
//Here results is of type Array[Either[Throwable, String]]
results foreach { result =>
result match {
Left(error) => //Handle error
Right(response) => //Handle response
}
}
}
There is a far better way:
val promises = urls.map {u =>
val service = url(u)
val promise = Http(service OK as.String).either
}
val listPromise = Future.sequence(promises)
listPromise.onComplete { whatever }
I agree with Alexey Romanov on his answer. Whatever way you choose to synchronize your http requests beware of the way your are processing the promises completion. Your intuition is correct in that concurrent access may appear on the state of the actor. The better way to handle this would be to do something like this:
def resultHandler(result: String) {
//on completion we are sending the result to the actor who triggered the call
//as a message
self ! HttpComplete(result)
}
and in the actor's receive function:
def receive = {
//PROCESS OTHER MESSAGES HERE
case HttpComplete(result) => //do something with the result
}
This way, you make sure that processing the http results won't violate the actor's state from the exterior, but from the actor's receive loop which is the proper way to do it
val nbOfResults = new java.util.concurrent.atomic.AtomicInteger(nbOfCalls)
// After particular call was ended
if (nbOfResults.decrementAndGet <= 0) {
// Do something
}
[EDIT] Removed old answer with AtomicReference CAS - while(true), compareAndSet, etc
I'm making a small caching actor with Akka 2 and to make the actor not block I perform all calculations inside futures. However a problem is that this actor also need to interact with with code that is not itself in an actor, so that I need to use the "ask" pattern to get a value.
My question is, how do I avoid wrapping the Future of my calculation inside another Future when using the ask pattern?
For example
val f = myCache ? GetOrCalc("myKey", myCalculation) // this will be a Future[Future[...]] but I would like a Future[...]
// meanwhile, inside the actor
def receive = {
case GetOrCalc(key, calculation) =>
if (keyNotExists) sender ! Future { calculation() } // calculation() is long-running
else sender ! cacheMap(key)
}
Ideally I could use the Future.pipeTo function but I'm afraid this doesn't get counted as a "response" for non-actor code
This is the solution:
val f = myCache ? GetOrCalc("myKey", myCalculation)
def receive = {
case GetOrCalc(key, calculation) =>
if (keyNotExists) Future { calculation() } pipeTo sender
else sender ! cacheMap(key)
}
Send-And-Receive-Future">http://doc.akka.io/docs/akka/2.0.3/scala/actors.html#Ask_Send-And-Receive-Future
Add onComplete to the calculation future.
def receive = {
case GetOrCalc(key, calculation) =>
if (keyNotExists) // calculation() is long-running
Future { calculation() } onComplete {
case Right(result) => result match {
case Some(value) => sender ! value
case None => sender ! Status.Failure(new Exception("Cannot find the value"))
}
case Left(ex) =>
sender ! Status.Failure(ex)
}
else sender ! cacheMap(key)
}
And there is an article about using Akka to build a cache system. http://letitcrash.com/post/30509298968/case-study-an-auto-updating-cache-using-actors