Created
May 28, 2014 15:05
-
-
Save davegurnell/a249754500818e470237 to your computer and use it in GitHub Desktop.
Sample code: dispatching jobs to actors and retrieving the results as futures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import akka.actor._ | |
import akka.pattern.ask | |
import akka.routing._ | |
import akka.util.Timeout | |
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
object Speaker { | |
case class EventuallySay(phrase: String) | |
case class ActuallySay(phrase: String) | |
} | |
class Speaker extends Actor { | |
import Speaker._ | |
def implicitly[A](implicit value: A): A = value | |
def receive = { | |
case msg @ EventuallySay(phrase) => | |
println("received " + msg) | |
context.system.scheduler.scheduleOnce(1 second, self, ActuallySay(phrase))( | |
implicitly[ExecutionContext], sender) | |
case msg @ ActuallySay(phrase) => | |
println("received " + msg) | |
sender ! phrase | |
} | |
} | |
object Main extends App { | |
import Speaker._ | |
implicit val timeout = Timeout(3 seconds) | |
val system = ActorSystem("noisy") | |
val speaker = system.actorOf(Props[Speaker].withRouter(RoundRobinRouter(5))) | |
val allResults: Future[List[Any]] = | |
Future.sequence( | |
for(i <- (0 until 100).toList) yield { | |
ask(speaker, EventuallySay(i.toString)) | |
} | |
) | |
allResults.foreach { results: List[Any] => | |
println(results) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment