SlideShare uma empresa Scribd logo
1 de 109
Baixar para ler offline
Above the Clouds:
   Introducing Akka
           Vojin Jovanovic, EPFL
          Philipp Haller, Typesafe

Based on material provided by the Akka team at Typesafe
The problem

It is way too hard to build:
1. correct highly concurrent systems
2. truly scalable systems
3. fault-tolerant systems that self-heal
...using “state-of-the-art” tools
Vision

Simpler
     Concurrency
     Scalability
     Fault-tolerance
Vision

...with a single unified
     Programming Model
     Managed Runtime
     Open Source Distribution
ARCHITECTURE



            CORE
           SERVICES
ARCHITECTURE
           Play!     Play-mini     Microkernel




                       Camel         AMQP
           TestKit
                     integration   integration




ADD-ON
MODULES
ARCHITECTURE
 Play!     Play-mini     Microkernel




             Camel         AMQP
 TestKit
           integration   integration




                                       TYPESAFE
                                        STACK
                                       ADD-ONS
WHERE IS AKKA USED?
                      SOME EXAMPLES:

FINANCE                                 TELECOM
•   Stock trend Analysis & Simulation
                                        •   Streaming media network gateways

•   Event-driven messaging systems
                                        SIMULATION
BETTING & GAMING                        •   3D simulation engines

•   Massive multiplayer online gaming
                                        E-COMMERCE
•   High throughput and transactional
                                        •   Social media community sites
    betting
Akka Actors
one tool in the toolbox
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
Actor

Behavior



 State
Event-
 driven

Actor

Behavior



 State
Event-
 driven

Actor

Behavior



 State
Event-
 driven

Actor

Behavior



 State
Event-
 driven

Actor

Behavior



 State
Event-
 driven

Actor

Behavior



 State
Actor

Behavior



 State
Event-
 driven

Actor

Behavior



 State
Actors
case object Tick

class Counter extends Actor {
  var counter = 0

    def receive = {
      case Tick =>
        counter += 1
        println(counter)
    }
}


            Scala API
Actors
class Counter extends UntypedActor {
  int counter = 0;

    void onReceive(Object msg) {
      if (msg.equals(“Tick”)) {
        counter += 1;
        System.out.println(counter);
      }
    }
}


                Java API
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
Create Application

val conf = ConfigFactory.load(“application”)

val system = ActorSystem(“my-app”, conf)




                 Scala API
Create Application
Config conf =
  ConfigFactory.load(“application”);

 ActorSystem system =
   ActorSystem.create(“my-app”, conf);



                Java API
Create Actors

val counter = system.actorOf(Props[Counter])



          counter is an ActorRef
          Creates a top-level actor

                  Scala API
Create Actors

ActorRef counter =
  system.actorOf(new Props(Counter.class));



          Creates a top-level actor


                  Java API
Stop actors

       system.stop(counter)




...also stops all actors in the hierarchy below
Send: !

counter ! Tick



  fire-forget

   Scala API
...or use tell

 counter tell Tick


     fire-forget

      Scala API
...or use tell

counter.tell(tick);


     fire-forget

      Java API
Send: ?
import akka.patterns.ask

// returns a future
val future = actor ? message

future onSuccess {
  case x => println(x)
}


      returns a Future
         Scala API
Reply
class SomeActor extends Actor {
  def receive = {
    case User(name) =>
      // reply to sender
      sender ! (“Hi ” + name)
  }
}



           Scala API
Reply
class 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
...or use ask
import akka.patterns.ask

// returns a future
val future = actor ask message

future onSuccess {
  case x => println(x)
}



          Scala API
...or use ask
import 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
Future
val f = Promise[String]()

f onComplete { ... }
  onSuccess { ... }
  onFailure { ... }
f foreach { ... }
f map { ... }
f flatMap { ... }
f filter { ... }
f zip otherF
f fallbackTo otherF

Await.result(f, 5 seconds)


           Scala API
Future
firstCompletedOf
                       fold
                                  reduce
       find
                     traverse
sequence



 Combinators for collections of Futures
Promise
 promise1.successful(...)
 promise2.failure(...)
 promise3.completeWith(future)




Promise is the write side of the Future
       Future is the read side
become
context become {
  // new body
  case NewMessage =>
    ...
}


      Scala API
become
context.become(new Procedure[Object]() {
  void apply(Object msg) {
    // new body
    if (msg instanceof NewMessage) {
      NewMessage newMsg = (NewMessage)msg;
      ...
    }
  }
});


                 Java API
unbecome

context.unbecome()
Scale up?
ThreadPoolExecutor
ThreadPoolExecutor
new ForkJoinPool
new ForkJoinPool
New
Remote Actors
Name

val actor = system.actorOf(Props[MyActor], “my-service”)




             Bind the actor to a name

                      Scala API
Name

ActorRef actor = system.actorOf(
  new Props(MyActor.class), “my-service”);




      Bind the actor to a name

                Java API
Deployment

    Actor name is virtual and
decoupled from how it is deployed
Deployment

If no deployment configuration exists
    then actor is deployed as local
Deployment

The same system can be configured
as distributed without code change
     (even change at runtime)
Deployment

Write as local but deploy as distributed
 in the cloud without code change
Deployment

 Allows runtime to dynamically
and adaptively change topology
Deployment configuration
   akka {
     actor {
       deployment {
         /my-service {
            router = "round-robin"
            nr-of-instances = 3
            target {
              nodes = ["wallace:2552", "gromit:2552"]
            }
          }
       }
     }
   }
Let it crash
fault-tolerance
The

Erlang
 model
Error
Kernel
Node 1   Node 2
Parental automatic supervision


// from within an actor
val child = context.actorOf(Props[MyActor], “my-actor”)




transparent and automatic fault handling by design


                      Scala API
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
Parental automatic supervision
           Guardian System Actor
Parental automatic supervision
           Guardian System Actor




            system.actorOf(Props[Foo], “Foo”)
Parental automatic supervision
              Guardian System Actor




        Foo   system.actorOf(Props[Foo], “Foo”)
Parental automatic supervision
                Guardian System Actor




        Foo




              context.actorOf(Props[A], “A”)
Parental automatic supervision
                Guardian System Actor




        Foo




       A      context.actorOf(Props[A], “A”)
Parental automatic supervision
              Guardian System Actor




        Foo                           Bar




                                            A
       A          C




              E                                 C
  B
                                      B

       D
Name resolution
           Guardian System Actor




     Foo                           Bar




                                         A
    A          C




           E                                 C
B
                                   B

     D
Name resolution
                 Guardian System Actor



    /Foo

           Foo                           Bar




                                               A
           A         C




                 E                                 C
B
                                         B

           D
Name resolution
                     Guardian System Actor



        /Foo

               Foo                           Bar



    /Foo/A
                                                   A
               A         C




                     E                                 C
B
                                             B

               D
Name resolution
                            Guardian System Actor



               /Foo

                      Foo                           Bar



           /Foo/A
                                                          A
                      A         C


/Foo/A/B

                            E                                 C
      B
                                                    B

                      D
Name resolution
                               Guardian System Actor



                  /Foo

                         Foo                           Bar



             /Foo/A
                                                             A
                         A         C


/Foo/A/B

                               E                                 C
      B
                                                       B

                         D
           /Foo/A/D
Supervision
class 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
Supervision
class 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
Manage failure
class 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
watch/unwatch
val buddy: ActorRef = ...

val watcher = system.actorOf(Props(
  new Actor {
    context.watch(buddy)

         def receive = {
           case t: Terminated => ...
         }
     }
))


                 Scala API
...and much much more
                       TestKit            FSM
  HTTP/REST
                    EventBus        Pub/Sub

Durable Mailboxes                Camel
                                              IO
       Microkernel         SLF4J
                                         AMQP
  ZeroMQ              Dataflow
                                    Transactors
       Agents          Spring
get it and learn more
       http://akka.io
    http://typesafe.com
Typesafe Console
Typesafe Console
Akka 2.1+
The runtime provides

    Decentralized P2P gossip-based
  cluster membership (dynamo-style
   w/ vector clocks, hand-off on fail-
               over etc.)
The runtime provides

  Automatic adaptive cluster rebalancing
The runtime provides

  Automatic cluster-wide deployment
The runtime provides

  Highly available configuration service
The runtime provides

  Automatic replication with automatic
      fail-over upon node crash
The runtime provides

   Transparent and user-configurable
            load-balancing
Akka Node
Akka Node
val ping = actorOf(Props[Ping], “ping”)
val pong = actorOf(Props[Pong], “pong”)

ping ! Ball(pong)
Akka Node
val ping = actorOf(Props[Ping], “ping”)
val pong = actorOf(Props[Pong], “pong”)

ping ! Ball(pong)




Ping                           Pong
Akka Node

    Akka
Cluster Node




               Ping   Pong
Akka
                               Cluster Node



   Akka Node

    Akka                                                        Akka
Cluster Node                                                Cluster Node




                        Ping                  Pong




             Akka                                    Akka
         Cluster Node                            Cluster Node
Akka
                           Cluster Node




    Akka                                                   Akka
Cluster Node                                           Cluster Node




                    Ping                  Pong




         Akka                                   Akka
     Cluster Node                           Cluster Node
Akka
                               Cluster Node




    Akka                                                           Akka
Cluster Node           akka {                                  Cluster Node
                         actor {
                           deployment {
                             /pong {
                                router = "round-robin"
                                nr-of-instances = 3
                              }
                           }
                    Ping }                       Pong
                       }




         Akka                                           Akka
     Cluster Node                                   Cluster Node
Akka
                                Pong
                            Cluster Node




    Akka                                                        Akka
    Ping                                                        Pong
Cluster Node        akka {                                  Cluster Node
                      actor {
                        deployment {
                          /pong {
                             router = "round-robin"
                             nr-of-instances = 3
                           }
                        }
                      }
                    }




         Akka                                        Akka
         Pong
     Cluster Node                                Cluster Node
Akka
                                Pong
                            Cluster Node




    Akka                                                        Akka
    Ping                                                        Pong
Cluster 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
Develop
Migration
Scala IDE   sbt
                  Manager
Run



                  Migration
Scala IDE   sbt
                  Manager
Scala         Akka           Play




                            Migration
Scala IDE      sbt
                            Manager
Manage



       Scala         Akka               Play




                                Migration
Scala IDE      sbt
                                Manager
Typesafe                                           Typesafe
                                           Provisioning
               Subscription                                         Console




       Scala                        Akka                     Play




                                                     Migration
Scala IDE                     sbt
                                                     Manager
Typesafe                                           Typesafe
                                           Provisioning
               Subscription                                         Console




       Scala                        Akka                     Play




                                                     Migration
Scala IDE                     sbt
                                                     Manager
live demo

http://console-demo.typesafe.com
sample video
      of the
Typesafe Console
sample video
      of the
Typesafe Console
EOF

Mais conteúdo relacionado

Semelhante a Akka JUGL 2012

GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GPars
GR8Conf
 
Akka: Distributed by Design
Akka: Distributed by DesignAkka: Distributed by Design
Akka: Distributed by Design
patriknw
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
Fwdays
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
Skills Matter
 
Java Intro
Java IntroJava Intro
Java Intro
backdoor
 

Semelhante a Akka JUGL 2012 (20)

First glance at Akka 2.0
First glance at Akka 2.0First glance at Akka 2.0
First glance at Akka 2.0
 
Akka (BeJUG)
Akka (BeJUG)Akka (BeJUG)
Akka (BeJUG)
 
Testing akka-actors
Testing akka-actorsTesting akka-actors
Testing akka-actors
 
Akka Actors: an Introduction
Akka Actors: an IntroductionAkka Actors: an Introduction
Akka Actors: an Introduction
 
Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0Building Massively Scalable application with Akka 2.0
Building Massively Scalable application with Akka 2.0
 
a million bots can't be wrong
a million bots can't be wronga million bots can't be wrong
a million bots can't be wrong
 
Василий Ременюк «Курс молодого подрывника»
Василий Ременюк «Курс молодого подрывника» Василий Ременюк «Курс молодого подрывника»
Василий Ременюк «Курс молодого подрывника»
 
GR8Conf 2011: GPars
GR8Conf 2011: GParsGR8Conf 2011: GPars
GR8Conf 2011: GPars
 
Akka: Distributed by Design
Akka: Distributed by DesignAkka: Distributed by Design
Akka: Distributed by Design
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
Con-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With JavassistCon-FESS 2015 - Having Fun With Javassist
Con-FESS 2015 - Having Fun With Javassist
 
Monitoring and Tuning GlassFish
Monitoring and Tuning GlassFishMonitoring and Tuning GlassFish
Monitoring and Tuning GlassFish
 
Monitoring And Tuning Glass Fish In The Wild Community One 2009
Monitoring And Tuning Glass Fish In The Wild   Community One 2009Monitoring And Tuning Glass Fish In The Wild   Community One 2009
Monitoring And Tuning Glass Fish In The Wild Community One 2009
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Akka london scala_user_group
Akka london scala_user_groupAkka london scala_user_group
Akka london scala_user_group
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Java Intro
Java IntroJava Intro
Java Intro
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Akka JUGL 2012