Skip to content

Instantly share code, notes, and snippets.

@davegurnell
Created May 28, 2014 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davegurnell/a249754500818e470237 to your computer and use it in GitHub Desktop.
Save davegurnell/a249754500818e470237 to your computer and use it in GitHub Desktop.
Sample code: dispatching jobs to actors and retrieving the results as futures
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