Akka. Do I have to execute all services / DAOs as actors?
In the Java world, it is considered optimal application development using a three-tier architecture (presentation tier, service tier, and DAO tier).
But my current application is using Scala and Akka. And in one of my actors, having received some message, I need to get a list of countries from the database. if I were using Java, chances are I would create an interface CountryService
and its implementation, as well as CountryDao
a corresponding implementation.
But what is Akka's way? Should I wrap up CountryService
an actor? I think this is a bad idea because in this case my actor, after receiving any message, will need to send another message to retrieve all countries and after it replies to the original sender.
source to share
This is purely based on my experience with Akka, and others will probably disagree.
If your Country Actor has no condition , then don't make it an actor. Just use the Scala API Future
and cast it back to the Actor that would call it. This way, the database call can be made in a completely different execution context from your participants (you shouldn't block calls inside Actors). If you are thinking about caching, then my opinion is that the cache is still stateless and using Guava Cache is thread safe and does the trick.
So it looks 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 where you might want to wrap this in it separately CountryActor
, but these are special: i.e. you rely heavily on the Actor path and want to access the service members along a specific path, want to handle errors on purpose, have some retry logic, etc.
source to share
The number of members is not related to the number of layers / services. You may have thousands of members per service or not at all. Depends on whether the actor is useful in this context.
The use of actors is useful for many things: hiding state, balancing workloads and dividing work among children, failover with a let it crash model: delegating dangerous work to children and choosing a surveillance strategy.
Creating and using actors is pretty cheap, as is sending messages. But of course you don't need them. Ask yourself: What benefits does an actor make here?
source to share