Created
October 6, 2015 11:55
-
-
Save bananaumai/26593e4ad76c5e617077 to your computer and use it in GitHub Desktop.
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.routing.RoundRobinPool | |
import akka.actor.SupervisorStrategy._ | |
import scala.concurrent.duration._ | |
import scala.util.Random | |
case object Run | |
case object Task | |
class ResumeException extends RuntimeException | |
class RestartException extends RuntimeException | |
class StopException extends RuntimeException | |
class Worker extends Actor { | |
var counter = 0 | |
override def preStart() = println(s"start - ${self.hashCode} counter: $counter") | |
def receive = { | |
case Task => { | |
val r = new Random | |
val num = r.nextInt | |
if (num % 7 == 0) throw new ResumeException | |
if (num % 11 == 0) throw new RestartException | |
if (num % 17 == 0) throw new StopException | |
for (i <- 1 to 100000) yield { | |
counter += 1 | |
} | |
println(s"alive - ${self.hashCode} mailbox: ${} counter: $counter") | |
} | |
} | |
} | |
class Master extends Actor { | |
val workerNum = 1; | |
val pool = context.actorOf(Props[Worker].withRouter(RoundRobinPool(workerNum)), name = "workerRouter") | |
def receive = { | |
case Run => pool.forward(Task) | |
} | |
override def supervisorStrategy = OneForOneStrategy() { | |
case _ : ResumeException => Resume | |
case _ : RestartException => Restart | |
case _ : StopException => Stop | |
} | |
} | |
object FailureHandlingAkka extends App { | |
val system = ActorSystem("failure-handling-akka") | |
val master = system.actorOf(Props[Master], "greeter") | |
import system.dispatcher | |
system.scheduler.schedule(0.seconds, 1.second, master, Run) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment