Akka Cookbook
eBook - ePub

Akka Cookbook

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

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

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
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.
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.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
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 Computer Science & Programming. We have over one million books available in our catalogue for you to explore.

Information

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

  1. Title Page
  2. Copyright
  3. Credits
  4. About the Authors
  5. About the Reviewer
  6. www.PacktPub.com
  7. Customer Feedback
  8. Preface
  9. Diving into Akka
  10. Supervision and Monitoring
  11. Routing Messages
  12. Using Futures and Agents
  13. Scheduling Actors and Other Utilities
  14. Akka Persistence
  15. Remoting and Akka Clustering
  16. Akka Streams
  17. Akka HTTP
  18. Understanding Various Akka patterns
  19. Microservices with Lagom