Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka. Should I implement all servicies/DAOs as actors?

Tags:

java

scala

akka

In Java world it's considered as best-practice to design application using 3-tier architecture (presentation layer, service-layer and DAO layer).

But my current application uses Scala and Akka. And in one of my actor, after receiving some message, I need retrieve list of countries from DB. if I had used Java, most likely I would create CountryService interface and it's implementation, as well as CountryDao with corresponding implementation.

But what is the Akka way to do it? Should I wrap CountryService by actor? I think it's bad idea, because in this case my actor after receiving some message will need to send another message to retrieve all countries and after it respond to original sender.

like image 415
WelcomeTo Avatar asked Sep 27 '22 20:09

WelcomeTo


2 Answers

This is purely based on my experience with Akka and others will probably disagree.

If your Country Actor would not have state then don't make it an Actor. Just simply use Scala's Future API and pipe it back to the Actor that would have called it. This way the database call can run on a totally different execution context from your Actors (you shouldn't do blocking calls inside of Actors). If you're thinking of caching then my opinion is that cache is still not really state and using a Guava Cache is threadsafe and does the trick.

So this would look something like this:

class MyActor(countryService: CountryService) extends Actor {
  // ...
  val result: Future[Countries] = countryService.getCountries
  result.pipeTo(self)
  // ...
  def recieve = {
    case Countries(c) => // use c
  }
  // ...
}

There are cases when you would want to wrap this into it's separate CountryActor, but those are special: i.e. you are heavily relying on Actor path and want to access service actors at a specific path, want to handle errors specially, have some retry logic, etc.

like image 106
Akos Krivachy Avatar answered Oct 20 '22 18:10

Akos Krivachy


The number of actors is unrelated to the number of layers/services. You can have thousands of actors per service, or none at all. Depends on whether the actor is useful in that context.

Using actors is useful for a lot of things: hiding state, load balancing and dividing work among children, fault tolerance with the "let it crash" model: delegating dangerous work to children and choosing a supervision strategy.

Creating and using actors is quite cheap, so is message sending. But of course you don't need them for everything. Ask yourself: what advantages does an actor bring here?

like image 39
Quizzie Avatar answered Oct 20 '22 20:10

Quizzie