Akka JUGL 2012

3,057 views

Published on

Indroduction to Akka (http://www.akka.io) by Vojin Jovanovic at the Lausanne Java User Group (http://jugl.myxwiki.org/xwiki/bin/view/Main/WebHome).

Published in: Technology, Education

Akka JUGL 2012

  1. 1. Above the Clouds: Introducing Akka Vojin Jovanovic, EPFL Philipp Haller, TypesafeBased on material provided by the Akka team at Typesafe
  2. 2. The problemIt is way too hard to build:1. correct highly concurrent systems2. truly scalable systems3. fault-tolerant systems that self-heal...using “state-of-the-art” tools
  3. 3. VisionSimpler Concurrency Scalability Fault-tolerance
  4. 4. Vision...with a single unified Programming Model Managed Runtime Open Source Distribution
  5. 5. ARCHITECTURE CORE SERVICES
  6. 6. ARCHITECTURE Play! Play-mini Microkernel Camel AMQP TestKit integration integrationADD-ONMODULES
  7. 7. ARCHITECTURE Play! Play-mini Microkernel Camel AMQP TestKit integration integration TYPESAFE STACK ADD-ONS
  8. 8. WHERE IS AKKA USED? SOME EXAMPLES:FINANCE TELECOM• Stock trend Analysis & Simulation • Streaming media network gateways• Event-driven messaging systems SIMULATIONBETTING & GAMING • 3D simulation engines• Massive multiplayer online gaming E-COMMERCE• High throughput and transactional • Social media community sites betting
  9. 9. Akka Actorsone tool in the toolbox
  10. 10. ACTOR CONCURRENCY• Actors = lightweight isolated processes• No shared state• Asynchronous message passing (non-blocking)• Sequential message processing (one message at a time)• Actor mailbox: queue of not-yet-processed messages
  11. 11. ActorBehavior State
  12. 12. Event- drivenActorBehavior State
  13. 13. Event- drivenActorBehavior State
  14. 14. Event- drivenActorBehavior State
  15. 15. Event- drivenActorBehavior State
  16. 16. Event- drivenActorBehavior State
  17. 17. ActorBehavior State
  18. 18. Event- drivenActorBehavior State
  19. 19. Actorscase object Tickclass Counter extends Actor { var counter = 0 def receive = { case Tick => counter += 1 println(counter) }} Scala API
  20. 20. Actorsclass Counter extends UntypedActor { int counter = 0; void onReceive(Object msg) { if (msg.equals(“Tick”)) { counter += 1; System.out.println(counter); } }} Java API
  21. 21. ACTOR SYSTEMS• Actors are created in the context of an actor system• Actor system = unit for managing shared facilities: scheduling services, configuration, logging etc.• Several actor systems with different configurations may co-exist within the same JVM instance (there is no global state within Akka itself)• There may be millions of actors within a single actor system
  22. 22. Create Applicationval conf = ConfigFactory.load(“application”)val system = ActorSystem(“my-app”, conf) Scala API
  23. 23. Create ApplicationConfig conf = ConfigFactory.load(“application”); ActorSystem system = ActorSystem.create(“my-app”, conf); Java API
  24. 24. Create Actorsval counter = system.actorOf(Props[Counter]) counter is an ActorRef Creates a top-level actor Scala API
  25. 25. Create ActorsActorRef counter = system.actorOf(new Props(Counter.class)); Creates a top-level actor Java API
  26. 26. Stop actors system.stop(counter)...also stops all actors in the hierarchy below
  27. 27. Send: !counter ! Tick fire-forget Scala API
  28. 28. ...or use tell counter tell Tick fire-forget Scala API
  29. 29. ...or use tellcounter.tell(tick); fire-forget Java API
  30. 30. Send: ?import akka.patterns.ask// returns a futureval future = actor ? messagefuture onSuccess { case x => println(x)} returns a Future Scala API
  31. 31. Replyclass SomeActor extends Actor { def receive = { case User(name) => // reply to sender sender ! (“Hi ” + name) }} Scala API
  32. 32. Replyclass SomeActor extends UntypedActor { void onReceive(Object msg) { if (msg instanceof User) { User user = (User) msg; // reply to sender getSender().tell(“Hi ” + user.name); } }} Java API
  33. 33. ...or use askimport akka.patterns.ask// returns a futureval future = actor ask messagefuture onSuccess { case x => println(x)} Scala API
  34. 34. ...or use askimport static akka.patterns.Patterns.ask;Future<Object> future = ask(actor, message, timeout);future.onSuccess(new OnSuccess<Object>() { public void onSuccess(String result) { System.out.println(result); }}); Java API
  35. 35. Futureval f = Promise[String]()f onComplete { ... } onSuccess { ... } onFailure { ... }f foreach { ... }f map { ... }f flatMap { ... }f filter { ... }f zip otherFf fallbackTo otherFAwait.result(f, 5 seconds) Scala API
  36. 36. FuturefirstCompletedOf fold reduce find traversesequence Combinators for collections of Futures
  37. 37. Promise promise1.successful(...) promise2.failure(...) promise3.completeWith(future)Promise is the write side of the Future Future is the read side
  38. 38. becomecontext become { // new body case NewMessage => ...} Scala API
  39. 39. becomecontext.become(new Procedure[Object]() { void apply(Object msg) { // new body if (msg instanceof NewMessage) { NewMessage newMsg = (NewMessage)msg; ... } }}); Java API
  40. 40. unbecomecontext.unbecome()
  41. 41. Scale up?
  42. 42. ThreadPoolExecutor
  43. 43. ThreadPoolExecutor
  44. 44. new ForkJoinPool
  45. 45. new ForkJoinPool
  46. 46. NewRemote Actors
  47. 47. Nameval actor = system.actorOf(Props[MyActor], “my-service”) Bind the actor to a name Scala API
  48. 48. NameActorRef actor = system.actorOf( new Props(MyActor.class), “my-service”); Bind the actor to a name Java API
  49. 49. Deployment Actor name is virtual anddecoupled from how it is deployed
  50. 50. DeploymentIf no deployment configuration exists then actor is deployed as local
  51. 51. DeploymentThe same system can be configuredas distributed without code change (even change at runtime)
  52. 52. DeploymentWrite as local but deploy as distributed in the cloud without code change
  53. 53. Deployment Allows runtime to dynamicallyand adaptively change topology
  54. 54. Deployment configuration akka { actor { deployment { /my-service { router = "round-robin" nr-of-instances = 3 target { nodes = ["wallace:2552", "gromit:2552"] } } } } }
  55. 55. Let it crashfault-tolerance
  56. 56. TheErlang model
  57. 57. ErrorKernel
  58. 58. Node 1 Node 2
  59. 59. Parental automatic supervision// from within an actorval child = context.actorOf(Props[MyActor], “my-actor”)transparent and automatic fault handling by design Scala API
  60. 60. Parental automatic supervision // from within an actor ActorRef child = getContext().actorOf( new Props(MyActor.class), “my-actor”);transparent and automatic fault handling by design Java API
  61. 61. Parental automatic supervision Guardian System Actor
  62. 62. Parental automatic supervision Guardian System Actor system.actorOf(Props[Foo], “Foo”)
  63. 63. Parental automatic supervision Guardian System Actor Foo system.actorOf(Props[Foo], “Foo”)
  64. 64. Parental automatic supervision Guardian System Actor Foo context.actorOf(Props[A], “A”)
  65. 65. Parental automatic supervision Guardian System Actor Foo A context.actorOf(Props[A], “A”)
  66. 66. Parental automatic supervision Guardian System Actor Foo Bar A A C E C B B D
  67. 67. Name resolution Guardian System Actor Foo Bar A A C E CB B D
  68. 68. Name resolution Guardian System Actor /Foo Foo Bar A A C E CB B D
  69. 69. Name resolution Guardian System Actor /Foo Foo Bar /Foo/A A A C E CB B D
  70. 70. Name resolution Guardian System Actor /Foo Foo Bar /Foo/A A A C/Foo/A/B E C B B D
  71. 71. Name resolution Guardian System Actor /Foo Foo Bar /Foo/A A A C/Foo/A/B E C B B D /Foo/A/D
  72. 72. Supervisionclass MySupervisor extends Actor { def supervisorStrategy = OneForOneStrategy({ case _: ActorKilledException => Stop case _: ArithmeticException => Resume case _: Exception => Restart case _ => Escalate   },   maxNrOfRetries = None,   withinTimeRange = None) def receive = { case NewUser(name) => ... = context.actorOf[User](name) }} Scala API
  73. 73. Supervisionclass MySupervisor extends Actor { def supervisorStrategy = AllForOneStrategy OneForOneStrategy({ case _: ActorKilledException => Stop case _: ArithmeticException => Resume case _: Exception => Restart case _ => Escalate   },   maxNrOfRetries = None,   withinTimeRange = None) def receive = { case NewUser(name) => ... = context.actorOf[User](name) }} Scala API
  74. 74. Manage failureclass FaultTolerantService extends Actor { ... override def preRestart( reason: Throwable, message: Option[Any]) = { ... // clean up before restart } override def postRestart(reason: Throwable) = { ... // init after restart }} Scala API
  75. 75. watch/unwatchval buddy: ActorRef = ...val watcher = system.actorOf(Props( new Actor { context.watch(buddy) def receive = { case t: Terminated => ... } })) Scala API
  76. 76. ...and much much more TestKit FSM HTTP/REST EventBus Pub/SubDurable Mailboxes Camel IO Microkernel SLF4J AMQP ZeroMQ Dataflow Transactors Agents Spring
  77. 77. get it and learn more http://akka.io http://typesafe.com
  78. 78. Typesafe Console
  79. 79. Typesafe Console
  80. 80. Akka 2.1+
  81. 81. The runtime provides Decentralized P2P gossip-based cluster membership (dynamo-style w/ vector clocks, hand-off on fail- over etc.)
  82. 82. The runtime provides Automatic adaptive cluster rebalancing
  83. 83. The runtime provides Automatic cluster-wide deployment
  84. 84. The runtime provides Highly available configuration service
  85. 85. The runtime provides Automatic replication with automatic fail-over upon node crash
  86. 86. The runtime provides Transparent and user-configurable load-balancing
  87. 87. Akka Node
  88. 88. Akka Nodeval ping = actorOf(Props[Ping], “ping”)val pong = actorOf(Props[Pong], “pong”)ping ! Ball(pong)
  89. 89. Akka Nodeval ping = actorOf(Props[Ping], “ping”)val pong = actorOf(Props[Pong], “pong”)ping ! Ball(pong)Ping Pong
  90. 90. Akka Node AkkaCluster Node Ping Pong
  91. 91. Akka Cluster Node Akka Node Akka AkkaCluster Node Cluster Node Ping Pong Akka Akka Cluster Node Cluster Node
  92. 92. Akka Cluster Node Akka AkkaCluster Node Cluster Node Ping Pong Akka Akka Cluster Node Cluster Node
  93. 93. Akka Cluster Node Akka AkkaCluster Node akka { Cluster Node actor { deployment { /pong { router = "round-robin" nr-of-instances = 3 } } Ping } Pong } Akka Akka Cluster Node Cluster Node
  94. 94. Akka Pong Cluster Node Akka Akka Ping PongCluster Node akka { Cluster Node actor { deployment { /pong { router = "round-robin" nr-of-instances = 3 } } } } Akka Akka Pong Cluster Node Cluster Node
  95. 95. Akka Pong Cluster Node Akka Akka Ping PongCluster Node akka { Cluster Node actor { deployment { /pong { router = "round-robin" nr-of-instances = 3 } } } } Fail-over Redirect references Akka Akka Pong Cluster Node Cluster Node
  96. 96. Develop
  97. 97. MigrationScala IDE sbt Manager
  98. 98. Run MigrationScala IDE sbt Manager
  99. 99. Scala Akka Play MigrationScala IDE sbt Manager
  100. 100. Manage Scala Akka Play MigrationScala IDE sbt Manager
  101. 101. Typesafe Typesafe Provisioning Subscription Console Scala Akka Play MigrationScala IDE sbt Manager
  102. 102. Typesafe Typesafe Provisioning Subscription Console Scala Akka Play MigrationScala IDE sbt Manager
  103. 103. live demohttp://console-demo.typesafe.com
  104. 104. sample video of theTypesafe Console
  105. 105. sample video of theTypesafe Console
  106. 106. EOF

×