Hands-On Akka Actor Programming
Total Page:16
File Type:pdf, Size:1020Kb
Distributed Data Management Thorsten Papenbrock Felix Naumann Akka Actor Programming F-2.03/F-2.04, Campus II Hasso Plattner Institut Akka Actor Programming Hands-on . Actor Model (Recap) . Basic Concepts . Runtime Architecture . Demo . Messaging . Parallelization . Remoting . Clustering . Patterns . Homework Thorsten Papenbrock Slide 2 Actor Model (Recap) Actor Programming Object-oriented Actor Task-oriented programming programming programming . Objects encapsulate . Actors encapsulate . Application split down state and behavior state and behavior into task graph . Objects communicate . Actors communicate . Tasks are scheduled with each other with each other and executed . Actor activities are transparently Separation of concerns scheduled and makes applications executed transparently Decoupling of tasks Distributed Data Management easier to build and and resources allows maintain. for asynchronous and Akka Actor Combines the Programming advantages of object- parallel programming. and task-oriented Thorsten Papenbrock programming. Slide 3 Actor Model (Recap) Actor Model Actor 1 Actor 2 Actor Model . A stricter message-passing model that treats actors as the universal primitives of concurrent computation . Actor: . Computational entity (private state/behavior) . Owns exactly one mailbox . Reacts on messages it receives (one message at a time) . Actor reactions: “The actor model retainedDistributed more Data of . Send a finite number of messages to other actors what I thought wereAnalytics good features of the objectEncoding idea” and . Create a finite number of new actors Alan Kay, pioneer of objectEvolution orientation . Change own state, i.e., behavior for next message Thorsten Papenbrock . Actor model prevents many parallel programming issues Slide 4 (race conditions, locking, deadlocks, …) Actor Model (Recap) Actor Model Actor 1 Actor 2 Advantages over pure RPC . Fault-tolerance: . “Let it crash!” philosophy to heal from unexpected errors . Automatic restart of failed actors; resend/re-route of failed messages Errors are expected to happen and implemented into the model: . Deadlock/starvation prevention: . Asynchronous messaging and private state actors prevent many parallelization issues Distributed Data . Parallelization: Management Akka Actor . Actors process one message at a time but different actors operate Programming independently (parallelization between actors not within an actor) . Actors may spawn new actors if needed (dynamic parallelization) Thorsten Papenbrock Slide 5 Actor Model (Recap) Actor Model Actor 1 Actor 2 Popular Actor Frameworks . Erlang: . Actor framework already included in the language . First popular actor implementation . Special: Native language support and strong actor isolation . Akka: . Actor framework for the JVM (Java and Scala) . Most popular actor implementation (at the moment) Distributed Data . Special: Actor Hierarchies Management Akka Actor . Orleans: Programming . Actor framework for Microsoft .NET Thorsten Papenbrock . Special: Virtual Actors (persisted state and transparent location) Slide 6 Akka Actor Programming Hands-on . Actor Model (Recap) . Basic Concepts . Runtime Architecture . Demo . Messaging . Parallelization . Remoting . Clustering . Patterns . Homework Thorsten Papenbrock Slide 7 Basic Concepts Akka Toolkit and Runtime . A free and open-source toolkit and runtime for building concurrent and distributed applications on the JVM . Supports multiple programming models for concurrency, but emphasizes actor-based concurrency Distributed Data Management . Inspired by Erlang Akka Actor Programming . Written in Scala (included in the Scala standard library) . Offers interfaces for Java and Scala Thorsten Papenbrock Slide 8 Basic Concepts Akka Modules Akka Actors Akka Cluster Akka Streams Akka Http Core Actor Classes for the Asynchronous, Asynchronous, model classes resilient and non-blocking, streaming-first for concurrency elastic backpressured, HTTP server and and distribution distribution over reactive stream client classes multiple nodes classes Cluster Sharding Akka Persistence Distributed Data Alpakka Distributed Data Management Classes to Classes to Classes for an Stream decouple actors persist actor eventually connector Akka Actor from their state for fault consistent, classes to other Programming locations tolerance and distributed, technologies referencing state restore replicated key- Thorsten Papenbrock them by identity after restarts value store Slide 9 <dependencies> Maven – pom.xml Basic Concepts <dependency> <groupId>com.typesafe.akka</groupId> Small Setup <artifactId>akka-actor_${scala.version}</artifactId> <version>2.5.3</version> </dependency> Base actor library <dependency> actors, supervision, scheduling, … <groupId>com.typesafe.akka</groupId> <artifactId>akka-remote_${scala.version}</artifactId> Remoting library <version>2.5.3</version> remote actors, heartbeats … </dependency> <dependency> Logger library <groupId>com.typesafe.akka</groupId> logging event bus for akka actors <artifactId>akka-slf4j_${scala.version}</artifactId> <version>2.5.3</version> </dependency> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-testkit_${scala.version}</artifactId> Distributed Data Testing library <version>2.5.3</version> Management TestKit class, expecting messages, … </dependency> Akka Actor Kryo library <dependency> Programming Custom serialization with Kryo <groupId>com.twitter</groupId> <artifactId>chill-akka_${scala.version}</artifactId> Thorsten Papenbrock <version>0.9.2</version> Slide 10 </dependency> </dependencies> Basic Concepts Akka Actors State Mailbox Actor 1 Actor 2 Behavior . Actor = State + Behavior + Mailbox . Communication: . Sending messages to mailboxes Distributed Data . Unblocking, fire-and-forget Mutable messages are possible, Management but don’t use them! Akka Actor . Messages: Programming . Immutable, serializable objects Thorsten Papenbrock . Object classes are known to both sender and receiver Slide 11 . Receiver interprets a message via pattern matching Basic Concepts Akka Actors State Called in default Mailbox actor constructor Actor 1 Actor 2 and set as the actor‘s behavior Behavior public class Worker extends AbstractActor { Inherit default actor behavior, @Override state and mailbox implementation public Receive createReceive() { return receiveBuilder() The Receive class performs .match(String.class, this::respondTo) pattern matching and de-serialization .matchAny(object -> System.out.println("Could not understand received message")) Distributed Data Management .build(); A builder pattern for constructing } a Receive object with otherwise Akka Actor private void respondTo(String message) { many constructor arguments Programming System.out.println(message); this.sender().tell("Received your message, thank you!", this.self()); Thorsten Papenbrock } Send a response to the sender of the last message Slide 12 } (asynchronously, non-blocking) Basic Concepts Akka Actors State Mailbox Actor 1 Actor 2 Behavior public class Worker extends AbstractActor { The message types (= classes) @Override define how the actor reacts public Receive createReceive() { return receiveBuilder() .match(String.class, s -> this.sender().tell("Hello!", this.self())) .match(Integer.class, i -> this.sender().tell(i * i, this.self())) Distributed Data .match(Doube.class, d -> this.sender().tell(d > 0 ? d : 0, this.self())) Management .match(MyMessage.class, s -> this.sender().tell(new YourMessage(), this.self())) Akka Actor Programming .matchAny(object -> System.out.println("Could not understand received message")) .build(); } Thorsten Papenbrock } Slide 13 Basic Concepts Akka Actors State Mailbox Actor 1 Actor 2 Behavior public class Worker extends AbstractLoggingActor { @Override public Receive createReceive() { return receiveBuilder() .match(String.class, s -> this.sender().tell("Hello!", this.self())) .match(Integer.class, i -> this.sender().tell(i * i, this.self())) Distributed Data .match(Doube.class, d -> this.sender().tell(d > 0 ? d : 0, this.self())) Management .match(MyMessage.class, s -> this.sender().tell(new YourMessage(), this.self())) Akka Actor Programming .matchAny(object -> this.log().error("Could not understand received message")) .build(); } AbstractLoggingActor Thorsten Papenbrock } provides propper logging Slide 14 Basic Concepts Akka Actors State Mailbox Actor 1 Actor 2 Behavior public class Worker extends AbstractLoggingActor { Good practice: public static class MyMessage implements Serializable {} Actors define their messages (provides a kind of interface description) @Override public Receive createReceive() { Distributed Data return receiveBuilder() Management .match(MyMessage.class, s -> this.sender().tell(new OtherActor.YourMessage(), this.self())) Akka Actor Programming .matchAny(object -> this.log().error("Could not understand received message")) .build(); } Thorsten Papenbrock } Slide 15 Basic Con. public class WorkerTest { Testing private ActorSystem actorSystem; @Before public void setUp() { this.actorSystem = ActorSystem.create(); } @Test public void shouldWorkAsExpected() { new TestKit(this.actorSystem) {{ ActorRef worker = actorSystem.actorOf(Worker.props()); worker.tell(new Worker.WorkMessage(73), this.getRef()); Master.ResultMessage expectedMsg = new Master.ResultMessage(42); this.expectMsg(Duration.create(3, "secs"), expectedMsg); }}; Distributed Data } Management Akka Actor @After Programming public void tearDown() { this.actorSystem.terminate(); Thorsten Papenbrock } Slide 16 } Basic Concepts Some