Integrating Apache Akka with Spring Boot

Integrating Apache Akka with Spring Boot

Apache Akka is a set of libraries based on “Actor concurrency model” which  allows to build highly scalable and resilient systems. So often we might need to use Akka and Spring framework together to use spring dependency injection features within Akka actors.

Akka actors and Spring beans have a different lifecycle management systems and these two cannot be used together directly. Akka provides mechanism called Akka extensions, which can be used to integrate akka into different frameworks. So let’s see how it works with Spring boot.

Dependencies

Here I’ve used the latest spring boot and akka dependencies to demonstrate the integration process.

Configuration

First we have to create a class that implements akka.actor.IndirectActorProducer and configure how to create actors using spring ApplicationContext. Here there are two constructors one with option to pass Object array of parameters. This array is supposed to pass Actor constructor parameters if needed.

Then the following configuration is used to create the actual integration between Spring and Akka using Akka Extention. An extension is a singleton instance created per actor system. It consists of an extension class itself, which implements the marker interface Extension, and an extension id class which inherits AbstractExtensionId.

Finally we need to create a marker interface to define how a actor should run in spring. This @Actor annotaion needs to added to every actor.

Defining an Actor

First let’s define a simple service to print a message

Then we’ll create a new Actor and inject the above class to it to use its functionalities. Notice how the @Actor annotation was used and how the service was injected to the actor.

Let’s run it

First we’ll create a ActorSystem and initialize the TestActor using that system. Then we’ll pass a simple “hello world” message to the actor.

Source code for the example can be found here

That’s it.

Thank you for taking the time to read this.

Leave a Comment

%d bloggers like this: