Akka Cookbook
eBook - ePub

Akka Cookbook

Hector Veiga Ortiz, Piyush Mishra

Share book
  1. 414 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Akka Cookbook

Hector Veiga Ortiz, Piyush Mishra

Book details
Book preview
Table of contents
Citations

About This Book

Learn how to use the Akka framework to build effective applications in ScalaAbout This Book• Covers a discussion on Lagom—the newest launched Akka framework that is built to create complex microservices easily• The recipe approach of the book allows the reader to know important and independent concepts of Scala and Akka in a seamless manner• Provides a comprehensive understanding of the Akka actor model and implementing it to create reactive web applicationsWho This Book Is ForIf you are a Scala developer who wants to build scalable and concurrent applications, then this book is for you. Basic knowledge of Akka will help you take advantage of this book.What You Will Learn• Control an actor using the ContolAware mailbox• Test a fault-tolerant application using the Akka test kit• Create a parallel application using futures and agents• Package and deploy Akka application inside Docker• Deploy remote actors programmatically on different nodes• Integrate Streams with Akka actors• Install Lagom and create a Lagom projectIn DetailAkka is an open source toolkit that simplifies the construction of distributed and concurrent applications on the JVM. This book will teach you how to develop reactive applications in Scala using the Akka framework.This book will show you how to build concurrent, scalable, and reactive applications in Akka. You will see how to create high performance applications, extend applications, build microservices with Lagom, and more.We will explore Akka's actor model and show you how to incorporate concurrency into your applications. The book puts a special emphasis on performance improvement and how to make an application available for users. We also make a special mention of message routing and construction.By the end of this book, you will be able to create a high-performing Scala application using the Akka framework.Style and approachThis highly practical recipe-based approach will allow you to build scalable, robust, and reactive applications using the Akka framework.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Akka Cookbook an online PDF/ePUB?
Yes, you can access Akka Cookbook by Hector Veiga Ortiz, Piyush Mishra in PDF and/or ePUB format, as well as other popular books in Informatik & Programmierung in Java. We have over one million books available in our catalogue for you to explore.

Information

Year
2017
ISBN
9781785288364

Understanding Various Akka patterns

In this chapter, we will cover the following recipes:
  • The Master Slave work pulling pattern
  • Ordered termination of actors
  • Shutdown patterns in Akka
  • Scheduling periodic messages to an actor
  • Throttling of messages while sending them to an actor
  • Balancing workload across actors
  • The aggregator pattern
  • The CountDownLatch pattern
  • Finite-state machine
  • The pausable actor pattern
  • Enveloping actor

Introduction

Throughout the previous chapters of the book, we have looked at how actors behave and how we can easily create distributed, concurrent and failure-tolerant applications by combining them. Also, actors can be used to create more complex libraries. Two good examples are Akka Streams and Akka HTTP. However, many other use cases require the use of actors themselves.
In this chapter, we will go through different actor pattern recipes to showcase useful common scenarios. We will learn important concepts in order to prevent mailbox message overflow using a Master Slave work pattern, pulling and balancing the workload across a set of actors. We will revisit how to stop children actors in an orderly manner by creating and an elegant way to identify when all actors in an actor system are stopped to terminate it, which might be handy in dynamic environments.
We will also explain the convenient API Akka provided to easily create Finite State Machines just by providing a set of states and events. Moreover, we will learn different enterprise integration patterns, such as Aggregator actor, Pausable actor, or Enveloping actor.

The Master Slave work pulling pattern

We have seen how Akka actors behave: each actor is able to process one message at a time and the rest of the messages get enqueued into the mailbox. If the code inside a given actor takes time, it's likely that the messages sent to that actor will pile up in the mailbox. If the mailbox type is unbounded, this could lead to an out-of-memory error. If it is bounded, it will probably drop messages when it reaches the maximum size.
To have better control over this kind of scenario, we can use the Master Slave work pulling pattern. This pattern lets a master actor control how many slaves can do work and distribute it among them. It only pushes work tasks to them when they are ready. Therefore, it is possible to manage the behavior of your system when all slaves are busy doing work. For example, we could slow the consuming of data in case we are receiving messages from a message broker. This pattern is a primitive kind of back pressure mechanism. For a more sophisticated back pressure method, we could use Akka Streams directly, which provides built-in back pressure across all stages of the stream.
The Master Slave work pulling pattern has been heavily used by the industry to concurrently process independent tasks. This pattern is especially important in Akka since it is possible to seamlessly run slaves in different JVMs thanks to Akka Remote or Akka Cluster. In this recipe, we will explain how to achieve this pattern with actors and what is recommended in order to have a scalable system without any single point of failure.

Getting ready

To step through this recipe, we need to import te Hello-Akka project, which will include a bare Scala sbt project that brings the Akka dependency.

How to do it...

For this recipe, we need to perform the following steps:
  1. Let's start with the master actor. This actor will keep a registry of worker actors and a queue of pending tasks. Create a file named MasterWorkPulling.scala inside the com.packt.chapter10 package. The content should look like this:
 package com.packt.chapter10

import akka.actor.{Actor, ActorLogging, ActorRef, Terminated}
import com.packt.chapter10.WorkerWorkPulling._
import com.packt.chapter10.MasterWorkPulling._
import scala.collection.mutable

object MasterWorkPulling {
case object JoinWorker
case object DeregisterWorker
}
  1. Additionally, let's define the master actor in the same MasterWorkPulling.scala file:
  class MasterWorkPulling(maxQueueSize: Int) extends Actor with ActorLogging {
val workers = mutable.Map.empty[ActorRef, WorkerState]
val pendingWork = mutable.Queue.empty[Work]

def receive = {
case JoinWorker =>
workers += sender -> Idle
context.watch(sender)
log.info(s"New worker registered [$sender]")
case Terminated(actorRef) => workers -= actorRef
case DeregisterWorker => workers -= sender
case PullWork if pendingWork.nonEmpty =>
log.info(s"Idle worker asking for work. Setting [$sender]
to [Working] state"
)
sender ! pendingWork.dequeue
workers += sender -> Working
case PullWork =>
log.info(s"Idle worker asking for work but no work
available. Setting [
$sender] to [Idle] state")
workers += sender -> Idle
case work : Work if pendingWork.size > maxQueueSize =>
log.info(s"Work received but max pending work tasks
reached. Rejecting [
$work]")
sender ! RejectWork(work)
case work : Work =>
pendingWork.enqueue(work)
workers.find(_._2 == Idle) match {
case Some((worker, _)) =>
val nextWork = pendingWork...

Table of contents