Akka Cookbook
eBook - ePub

Akka Cookbook

Hector Veiga Ortiz, Piyush Mishra

Condividi libro
  1. 414 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Akka Cookbook

Hector Veiga Ortiz, Piyush Mishra

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Akka Cookbook è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Akka Cookbook di Hector Veiga Ortiz, Piyush Mishra in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatik e Programmierung in Java. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2017
ISBN
9781785288364
Edizione
1
Argomento
Informatik

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...

Indice dei contenuti