Akka Cookbook - Vivek Mishra - E-Book

Akka Cookbook E-Book

Vivek Mishra

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

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

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 412

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Title Page

Akka Cookbook
Make your application fast, concurrent, and reactive through exciting recipes
Héctor Veiga Ortiz
Piyush Mishra

BIRMINGHAM - MUMBAI

Copyright

Credits

Authors

Héctor Veiga Ortiz

Piyush Mishra

Copy Editor

Stuti Shrivastava

Reviewer

Steve Fosdal

Project Coordinator 

Vaidehi Sawant

Commissioning Editor 

Kunal Parikh

Proofreader 

Safis Editing

Acquisition Editor 

Chaitanya Nair 

Indexer 

Francy Puthiry 

Content Development Editor 

Rohit Kumar Singh

Production Coordinator 

Nilesh Mohite

Technical Editor 

Vivek Pala

About the Authors

Héctor Veiga Ortiz is a software engineer specializing in real-time data integration. Recently, he has focused his work on different cloud technologies (such as AWS) to develop and run scalable, resilient, and high performing applications that are able to handle high volume, real-time data in diverse protocols and formats. To accomplish this task, he has been focusing his work on messaging systems such as Akka. He has also been working on microservice architectures with frameworks such as Lightbend’s Lagom. Additionally, he has a strong foundation in messaging broker knowledge, such as RabbitMQ and AMQP. Also, Héctor has a master’s degree in telecommunication engineering from the Universidad Politécnica de Madrid and a master’s degree in information technology and management from the Illinois Institute of Technology.

He currently works at HERE Technologies as part of the global traffic data integrations team and is actively developing scalable applications to consume data from several different sources. He heavily utilizes Akka to address the scalability and processing requirements. In the past, Héctor worked at Xaptum Technologies, a company dedicated to M2M technologies. Moreover, he has also contributed to the Akka project on a couple of occasions and is an active StackOverflow user on the akka tag.

Héctor has also worked as a technical reviewer on the books RabbitMQ Cookbook and RabbitMQ Essentials by Packt Publishing.

I would like to thank my family and friends for their support. I particular, I would like to acknowledge my family (my mother, Pilar; my sister, Paula; and my father, Jose Carlos), who has been supporting me from the other side of the globe. Above all, I would like to thank the love of my life, Laura. Thank you for backing me throughout this project and making my life better every single day.

Piyush Mishra is a professional with more than 4 years of experience of developing and designing fault-tolerant, scalable, distributed, highly performant systems using Scala, Akka, and Spark, and maintaining them across multiple servers. He is currently working as a software development engineer for R&D Labs at Pramati Labs.

He writes a blog on Scala, which you can find at https://piyushmishra889.wordpress.com/.

You can find him on LinkedIn at https://in.linkedin.com/in/piyush1989.

He also has presentations on Slideshare (http://www.slideshare.net/knoldus/reactive-programming-with-scala-and-akka), where he talks about reactive programming and applications and why we need it. He also talks about Scala, Akka, reactive applications, and their four principles.

I would like to thank my family: my father, Omkar Nath Mishra, and my wife, Laxmi, who encouraged me for writing this book. I am very thankful to Packt for the support for the entire duration of this project.

 

About the Reviewer

Steve Fosdal has been working in the software industry for more than a decade. He is currently focused on applying machine learning to real-time systems. His work involves using AWS, Spark, Akka, Kafka and Scala.

While getting his B.S. in physics from UW-Madison, he got interested in computational physics. His time spent working on N-body and quantum vortex simulations lead him to his current career.

He currently works as a big data software engineer at Avvo. Previously, he worked as a solution architect at Slalom and as a lead software engineer at HERE Technologies working on real-time data integration and predictive traffic.

You can find him online at http://fosdal.net.

He has also reviewed the book Mastering RabbitMQ by Packt Publishing.

I would like to thank my wife, Hilary, for her unbounded support for everything that I do.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.comand as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://goo.gl/rLMAk0.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Diving into Akka

Introduction

Creating an Akka Scala SBT project from scratch

Getting ready

How to do it...

Creating and understanding ActorSystem

Getting ready

How to do it...

How it works...

Why we need ActorSystem

Defining the actor's behavior and state

Getting ready

How to do it...

How it works...

There's more...

Sending messages to actors

Getting ready

How to do it...

How it works...

There's more...

Asking for a result from an actor

How to do it...

How it works...

There's more...

Communication between actors

Getting ready

How to do it...

How it works...

There's more...

Creating a custom mailbox for an actor

Getting ready

How to do it...

How it works...

Prioritizing messages that an actor receives

Getting ready

How to do it...

How it works...

Creating a control-aware mailbox for an actor

Getting ready

How to do it...

How it works...

Become/unbecome behavior of an actor

Getting ready

How to do it...

How it works...

Stopping an actor

Getting ready

How to do it...

How it works...

Supervision and Monitoring

Introduction

What is fault tolerance?

What is a component?

How Akka fits in between all of them?

Creating child actors of a parent actor

Getting ready

How to do it...

How it works...

Overriding the life cycle hooks of an actor

How to do it...

How it works...

Sending messages to actors and collecting responses

How to do it...

How it works...

Understanding OneForOneStrategy for actors

How to do it...

How it works...

Understanding AllForOneStrategy for actors

How to do it...

How it works...

Monitoring an actor life cycle using DeathWatch

How to do it...

How it works...

Routing Messages

Introduction

Where to use routers

Creating a SmallestMailboxPool of actors

Getting ready

How to do it...

How it works...

Creating a BalancingPool of actors

Getting ready

How to do it...

How it works...

Creating a RoundRobinPool of actors

Getting ready

How to do it...

How it works...

Creating a BroadcastPool of actors

Getting ready

How to do it...

How it works...

Creating a ScatterGatherFirstCompletedPool of actors

Getting ready

How it works...

Creating a TailChoppingPool of actors.

Getting ready

How it works...

Creating a ConsistentHashingPool of actors

Getting ready

How to do it...

How it works...

Creating a RandomPool of actors

Getting ready

How to do it...

How it works...

Sending specially handled messages to routers

Getting ready

How to do it...

How it works...

Creating a dynamically resizable pool of actors

Getting ready

How to do it...

Using Futures and Agents

Introduction

Using a future directly for a simple operation

Getting ready

How to do it...

How it works...

Using futures with actors

Getting ready

How to do it...

How it works...

Using futures inside actors

Getting ready

How to do it...

How it works...

Using for-comprehensions for futures

Getting ready

How to do it...

How it works...

Handling callback on futures

Getting ready

How to do it...

How it works...

Creating a simple parallel application using futures

Getting ready

How to do it...

How it works...

Reducing a sequence of futures

Getting ready

How to do it...

How it works...

Reading and updating agents

Getting ready

How to do it...

How it works...

Composing agents monadically

Getting ready

How to do it..

How it works...

Scheduling Actors and Other Utilities

Introduction

Scheduling an operation at a specified interval

Getting ready

How to do it...

How it works...

Scheduling an actor's operation at a specified interval

Getting ready

How to do it...

How it works...

Canceling a scheduled operation of the actor

Getting ready

How to do it...

How it works...

Creating a circuit breaker to avoid cascading failure

Getting ready

How to do it...

How it works...

How to introduce logging with actors

Getting ready

How to do it...

How it works...

Writing unit test for actors

Getting ready

How to do it...

How it works...

Packaging and deploying the Akka standalone application

Getting ready

How to do it...

How it works...

Packaging and deploying Akka application inside a Docker container

Getting ready

How to do it...

How it works...

Configurating Akka applications

Getting ready

How to do it...

How it works...

Akka Persistence

Introduction

Preparing an actor for persistence

Getting ready

How to do it...

How it works...

Recovering the state of an actor

Getting ready

How to do it...

How it works...

Safely shutting down a persistent actor

Getting ready

How to do it...

How it works...

Reducing recovery time using snapshots

Getting ready

How to do it...

How it works...

Creating a persistence FSM model

Getting ready

How to do it...

How it works...

Persisting the state to LevelDB

Getting ready

How to do it...

How it works...

Persisting the state to Cassandra

Getting ready

How to do it...

How it works...

Persisting the state to Redis

Getting ready

How to do it...

How it works...

Understanding event sourcing

Getting ready

How to do it...

How it works...

Handling failure in event sourcing

Getting ready

How to do it...

How it works...

Using persistence query

Getting ready

How to do it...

How it works...

Persistence query for LevelDB

Getting ready

How to do it...

How it works...

Remoting and Akka Clustering

Introduction

Enabling Akka applications for remoting

Getting ready

How to do it...

How it works...

Creating remote actors on different machines

Getting ready

How to do it...

How it works...

Looking up remote actors from different machines

Getting ready

How to do it...

How it works...

Deploying remote actors programmatically on different nodes

Getting ready

How to do it...

How it works...

Scaling out your application using remote actors

Getting ready

How to do it...

How it works

Creating a chat-based application using remote actors

Getting ready

How to do it...

How it works...

Enabling Akka clustering for your project

Getting ready

How to do it...

How it works...

Using Distributed Publish-Subscribe in the cluster

Getting ready

How to do it...

How it works...

Cluster Sharding

Getting ready

How to do it...

How it works...

Sharing data between nodes in an Akka cluster

Getting ready

How to do it...

How it works...

Creating a singleton actor across clusters

Getting ready

How to do it...

How it works...

See also

Akka Streams

Introduction

Creating simple Akka Streams

Getting ready

How to do it...

How it works...

How to transform streams and consume them

Getting ready

How to do it...

How it works...

Creating stream sources, flows, and sinks

Getting ready

How to do it...

How it works...

Custom stream processing

Getting ready

How to do it...

How it works...

Error handling in Akka streams

Getting ready

How to do it...

How it works...

Pipelining and parallelizing streams

Getting ready

How to do it...

How it works...

Working with streaming I/O

Getting ready

How to do it...

How it works...

Integrating streams with Akka actors

Getting ready

How to do it...

How it works...

Working with graphs

Getting ready

How to do it...

How it works...

Processing RabbitMQ messages with Akka streams

Getting ready

How to do it...

How it works...

Integrating Akka Streams with Kafka using Reactive Kafka

Getting ready

How to do it...

How it works...

Akka HTTP

Introduction

Creating a minimal HTTP server using Akka HTTP

Getting ready

How to do it...

How it works...

Consuming Akka HTTP services using a client-side API

Getting ready

How to do it...

How it works...

Writing routing DSL for HTTP servers

Getting ready

How to do it...

How it works...

Understanding the configuration of Akka HTTP

Getting ready

How to do it...

How it works...

Marshaling and unmarshaling data

Getting ready

How to do it...

How it works...

Encoding and decoding data

Getting ready

How to do it...

How it works...

Understanding directives

Getting ready

How to do it...

How it works...

Exception handling

Getting ready

How to do it...

How it works...

Uploading a file using Akka HTTP

Getting ready

How to do it...

How it works...

Building JSON support with Akka HTTP

Getting ready

How to do it...

How it works...

XML support with Akka HTTP

Getting ready

How to do it...

How it works...

Understanding Various Akka patterns

Introduction

The Master Slave work pulling pattern

Getting ready

How to do it...

How it works...

Ordered termination of actors

Getting ready

How to do it...

How it works...

Shutdown patterns in Akka

Getting ready

How to do it...

How it works...

Scheduling periodic messages to an actor

Getting ready

How to do it...

How it works...

Throttling of messages while sending them to an actor

Getting ready

How to do it...

How it works...

Balancing workload across actors

Getting ready

How it works...

How it works...

The aggregator pattern

Getting ready

How to do it...

How it works...

The CountDownLatch pattern

Getting ready

How to do it...

How it works...

Finite-state machine

Getting ready

How to do it...

How it works...

The pausable actor pattern

Getting ready

How to do it...

How it works...

Enveloping actor

Getting ready

How to do it...

How it works...

Microservices with Lagom

Introduction

Installing Lagom and creating a Lagom project

Getting ready

How to do it...

How it works...

Understanding the service locator

Getting ready

How to do it...

How it works...

Understanding service descriptors

Getting ready

How to do it...

How it works

Implementing Lagom services

Getting ready

How to do it...

How it works...

Consuming services

Getting ready

How to do it...

How it works...

Testing services

Getting ready

How to do it...

How it works...

Writing persistent and clustered services

Getting ready

How to do it...

How it works...

Running Lagom in production

Getting ready

How to do it...

How it works...

Integrating with Akka

Getting ready

How to do it...

How it works

Akka Cookbook

Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2017

Production reference: 1240517

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham 
B3 2PB, UK.

ISBN 978-1-78528-818-0

www.packtpub.com

Preface

Akka is a popular toolkit that helps develop concurrent, scalable, resilient, and reactive applications in the JVM thanks to the actor model. The toolkit has been around for some years, so we can consider it as a mature technology. Moreover, it has been successfully implemented by many companies, such as Cisco, Amazon.com, and Groupon. This book helps you understand how Akka (and all the modules around it) work and provides a set of useful recipes to easily achieve several of the most common tasks. It also includes an introductory chapter on Lagom, the latest microservices framework by Lightbend, the company behind the development of Akka.

What this book covers

Chapter 1, Diving into Akka, covers the basic concepts of Akka: actors, actor systems, mailboxes, and switching actor behaviors.

Chapter 2, Supervision and Monitoring, covers the actor life cycle, actor hierarchy, supervision, and monitoring.

Chapter 3, Routing Messages, covers the different types of group and pool router and how the Akka dispatcher works.

Chapter 4, Using Futures and Agents, covers how futures work and how well they integrate with the Akka toolkit. It also covers Akka agents.

Chapter 5, Scheduling Actors and Other Utilities, explains how the Akka scheduler works and contains various useful recipes about packaging, configuring, and running your Akka application.

Chapter 6, Akka Persistence, explains how to persist the state of an stateful actor to a variety of technologies, such as Apache Cassandra and Redis. It also covers different recovering strategies.

Chapter 7, Remoting and Akka Clustering, covers how to use Akka beyond a single JVM, either by using a well-known remote address or by joining a decentralized peer-to-peer-based cluster membership service.

Chapter 8, Akka Streams, covers the Akka Streams framework and how to integrate it with Akka and with third-party technologies.

Chapter 9, Akka HTTP, explains how to use Akka HTTP both on the client and server side. Also, it shows how to choose the API level depending on the use case.

Chapter 10, Understanding Various Akka Patterns, covers how to use different common programming patterns using Akka.

Chapter 11, Microservices with Lagom, introduces Lagom, the microservices framework from Lightbend. It provides information about conventions and how to create, configure, connect, and run microservices with Lagom.

What you need for this book

In this book, you will find recipes that provide examples that show the expected behavior. All code examples are written in the programming language Scala (http://www.scala-lang.org/). Akka also provides a Java API, which we will not be covering in the examples. Despite that, the rationale behind all the recipes work the same in either Java or Scala. This book can also be used by Java developers to understand the core concepts of the different recipes.

In addition to Scala, we use sbt (http://www.scala-sbt.org/) as the build tool for the examples in the book. Sbt not only does dependency management, but also helps us run our examples.

Finally, it is recommended (but not required) to use an IDE to develop the different recipes. IntelliJ IDEA or Scala IDE are two good examples of free IDEs to develop Scala applications.

Who this book is for

This book goes through many aspects of the Akka toolkit. From easy recipes, such as Sending messages to Actors, to advanced topics, such as Master Slave work pulling pattern, its aim is to provide useful examples and explanations of how to achieve different patterns with Akka. Even if you are just starting with Akka or you have already used it in the past, these pages will provide you with a deep understanding of Akka that can be applied to new tasks not covered in this book.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Akka-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Diving into Akka

In this chapter, we will cover the following recipes:

Creating an Akka Scala SBT project from scratch

Creating and understanding ActorSystem

Defining the actor's behavior and state

Sending messages to actors

Asking for a result from an actor

Communication between actors

Creating a custom mailbox for an actor

Prioritizing messages that an actor receives

Creating a control-aware mailbox for an actor

Become/unbecome behavior of an actor

Stopping an actor

Introduction

In today's world, computer hardware is becoming cheaper and more powerful, as we have multiple cores on a single CPU chip. As cores keep on increasing, with the increasing power of hardware, we need a state of the art software framework which can use these cores efficiently.

Akka is such a framework, or you can say, a toolkit, which utilizes the hardware cores efficiently and lets you write performant applications.

As we are living in big data world, a lot of traffic comes to our servers, and we want our servers to respond in milliseconds instead of seconds. Akka is here to scale up the application as the load on it increases.

We want our application to run day and night continuously with high availability--Akka is here to build fault tolerance for our application.

We want to run our application on a cluster of multiple machines--Akka is here to scale out our application across the data center.

Can we do all of this using the Java multithreading model? Maybe.

Our assumption is that most of our readers have worked with the Java multithreading model, and they are aware of the fact that it is very difficult to write multithreaded concurrent applications. This is because we have to manage low-level details like locking an object, releasing the lock on the object, notifying, waiting for threads to join each other to complete a task, and freeing up resources that a thread holds. It is difficult for us to write multithreaded programs, because we have to focus more on thread management details instead of focusing on business logic only.

Akka is a toolkit for writing truly concurrent, fault-tolerant, distributed, and scalable applications, which can run for days, months, and years without stopping, and can heal themselves in case of failure. It is very hard to write concurrent applications using the plain Java multithreading model, which also satisfies fault-tolerant, distributed, and scalable properties. Akka provides a high-level of abstraction to build such an application that satisfy these properties.

Thus, Akka provides a basic unit of abstraction of transparent distribution called actors, which form the basis for writing resilient, elastic, event-driven, and responsive systems.

Let's see what is meant by these properties:

Resilient

: Applications that can heal themselves, which means they can recover from failure, and will always be responsive, even in case of failure like if we get errors or exceptions

Elastic

: A system which is responsive under varying amount of workload, that is, the system always remains responsive, irrespective of increasing or decreasing traffic, by increasing or decreasing the resources allocated to service this workload

Message Driven

: A system whose components are loosely coupled with each other and communicate using asynchronous message passing, and which reacts to those messages by taking an action

Responsive

: A system that satisfies the preceding three properties is called responsive

A system that satisfies all four properties is called a reactive system.

Properties of reactive system
For more information, see Reactive manifesto (http://www.reactivemanifesto.org).

Before starting with recipes, let's take a look at the following the actor properties:

State

: An actor has internal state, which is mutated sequentially as messages are processed one by one.

Behavior

: An Actor reacts to messages which are sent to it by applying behavior on it.

Communication

: An actor communicates with other actors by sending and receiving messages to/from them.

Mailbox

: A mailbox is the queue of messages from which an actor picks up the message and processes it.

An actor's anatomy

Actors are message-driven, that is, they are passive and do nothing unless and until you send messages to them. Once you send them a message, they pick a thread from the thread pool which is also known as a dispatcher, process the message, and release the thread back to the thread pool.

Actors are also asynchronous by nature; they never block your current thread of execution, and continue to work on another thread.

Visit the Wikipedia link for an actor model (https://en.wikipedia.org/wiki/Actor_model) for details.

Let's start making recipes.

Creating an Akka Scala SBT project from scratch

Assuming that readers are Scala developers, it is obvious they have knowledge of SBT (Simple Build Tool) to build a Scala project.

Getting ready

To step through this recipe, you will need SBT installed on your machine. No other prerequisites are required.

If you don't have SBT installed on your machine, please visit the SBT manual installation page(http://www.scala-sbt.org/release/docs/Manual-Installation.html), and follow the instructions for the operating system you have.

SBT is used for building Scala projects as we have Maven for Java projects. However, both SBT and Maven are capable of building Scala, Java projects.

In this book, we will build our projects on the Ubuntu Linux operating system.

How to do it...

For creating an SBT project, we need to create a project directory, for example,

Hello-Akka

.

Following screenshot shows the creation of the project directory:

Creating the project directory

Descend to the directory and run command

sbt

. We will enter into the sbt prompt mode, Now run the following commands one by one, as shown in the next screenshot:

set name := "Hello-Akka"

set version := "1.0"

set scalaVersion: ="2.11.7"

session save

exit

This will create a build file called build.sbt and a target to put your class files into.

Edit the build file, and add the Akka actor dependency as follows:

libraryDependencies += "com.typesafe.akka" % "akka-actor_2.11" % "2.4.4"

We can select a specific Akka actor version against a specific Scala version in the maven repository:

Adding Akka dependency to build file

Run the command

sbt update

; it will download the Akka dependency. Now we have the Akka actor's capabilities in our project, and we are ready to write reactive programs.

The SBT (Simple Build tool), as the name suggests is a widely used tool for building Scala projects.

In step one, we create a project directory where we keep our source files, project build definition, and target, where class files are kept for runtime execution.

In step two, we create a project build definition file, called build.sbt, by executing simple sbt command.

In step three, we add a library dependency in the build file for the Akka actor to enable Akka capabilities.

In step four, we download the Akka dependency using the sbt update command, and our project is now ready for writing Akka-based applications.

This is how we can set up an Akka-based project.

Creating and understanding ActorSystem

In this small recipe, we will create and understand an ActorSystem. Since we are done with our initial setup of the Hello-Akka project, we don't need to make another project for it. We need to import the SBT project in an IDE like IntelliJ Idea.

Getting ready

If you are using IntelliJ Idea, then you must have Scala and the SBT plugin install on it.

For importing an SBT Scala project in IntelliJ Idea, visit the following website:https://www.jetbrains.com/help/idea/2016.1/getting-started-with-sbt.html?origin=old_help#import_project.

How it works...

In the recipe, we create a simple Scala object creating an ActorSystem, thereafter, we run the application.

Why we need ActorSystem

In Akka, an ActorSystem is the starting point of any Akka application that we write.

Technically, an ActorSystem is a heavyweight structure per application, which allocates n number of threads. Thus, it is recommended to create one ActorSystem per application, until we have a reason to create another one.

ActorSystem is the home for the actors in which they live, it manages the life cycle of an actor and supervises them.On creation, an ActorSystem starts three actors:

/user

- The guardian actor: All user-defined actors are created as a child of the parent actor user, that is, when you create your actor in the ActorSystem, it becomes the child of the user guardian actor, and this guardian actor supervises your actors. If the guardian actor terminates, all your actors get terminated as well.

/system

- The system guardian: In Akka, logging is also implemented using actors. This special guardian shut downs the logged-in actors when all normal actors have terminated. It watches the user guardian actor, and upon termination of the guardian actor, it initiates its own shutdown.

/

- The root guardian: The root guardian is the grandparent of all the so-called top-level actors, and supervises all the top-level actors. Its purpose is to terminate the child upon any type of exception. It sets the ActorSystem status as terminated if the guardian actor is able to terminate all the child actors successfully.

For more information on ActorSystem visit: http://doc.akka.io/docs/akka/2.4.1/general/actor-systems.html.

Defining the actor's behavior and state

In this recipe, we will define an actor, which will receive some messages, and apply its behavior to its state. After that, we will create that actor inside the actor system.

We will see what is meant by the terms behavior and the state of an actor.

Getting ready

To step through this recipe, we need to import the Hello-Akka project in any IDE, like intelliJ Idea, and ensure that SBT is installed on our machine to build and run the Scala project from the console.

How it works...

As we know from the previous recipe, the ActorSystem is a place where the actor lives.

In the preceding application, we define the actor with its state and behavior, and then create it inside Akka using the API provided by Akka.

In case of the summingactor, the state is the variable sum and the behavior is adding of the integer to the sum as soon as the message arrives.

There's more...

There are some recommended practices related to creation of actors. For more details, you can check out the following link:

http://doc.akka.io/docs/akka/current/scala/actors.html.

Sending messages to actors

Sending messages to actors is the first step for building a Akka based application as Akka is a message driven framework, so get started

Getting ready

In this recipe, we will learn how to send messages to actors. Prerequisites are the same as the previous recipes.

How it works...

Actors have methods to communicate with each other actors like tell (!) or ask (?) where the first one is fire and forget and the second returns a Future which means the response will come from that actor in the future.

As soon as you send the message to the actor, it receives the message, picks up an underlying Java thread from the thread pool, does it's work, and releases the thread. The actors never block your current thread of execution, thus, they are asynchronous by nature.

There's more...

Visit the following link to see more information on send messages:

http://doc.akka.io/docs/akka/current/scala/actors.html#Send_messages.

Asking for a result from an actor

In this recipe, we will ask the actor to give us the result that it computes. Prerequisites are the same as the previous recipes.

In the last recipe, you learnt how to send a message using the tell-and-forget pattern. In this recipe, you will learn how to get the result from an actor after it does something.

How it works...

We create an actor that computes Fibonacci number, and sends the result to the sender who sent him the message to compute the Fibonacci.

In the actor receive block, we send the Fibonacci result back to the sender. Actors, by nature, know who has sent them the message, thus we always have the sender present in the context of the receive block.

When you send a message to the actor using a question mark (?), it returns a future promising that you will get the result when the operation would be completed.

We will learn about futures in later chapters.

There's more...

To know more about sending messages to actors, go to the following link:

http://doc.akka.io/docs/akka/current/scala/actors.html#Send_messages.

Communication between actors

In an Akka-based application, there are many actors and they will have some way to communicate among themselves..

In this recipe, you will learn how two actors communicate with each other. For this, we need to import the same project, Hello-Akka, in our IDE. Prerequisites are the same as in the previous recipes.

Getting ready

To step through this recipe we will import the Hello-Akka project in our IDE and other prerequisites are same as before.