Akka Cookbook
eBook - ePub

Akka Cookbook

Hector Veiga Ortiz, Piyush Mishra

Compartir libro
  1. 414 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Akka Cookbook

Hector Veiga Ortiz, Piyush Mishra

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Akka Cookbook un PDF/ePUB en línea?
Sí, puedes acceder a Akka Cookbook de Hector Veiga Ortiz, Piyush Mishra en formato PDF o ePUB, así como a otros libros populares de Informatik y Programmierung in Java. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2017
ISBN
9781785288364
Edición
1
Categoría
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...

Índice