opyate
opyate

Reputation: 5428

Akka actors + Play! 2.0 Scala Edition best practices for spawning and bundling actor instances

My app gets a new instance of Something via an API call on a stateless controller. After I do my mission critical stuff (like saving it to my Postgres database and committing the transaction) I would now like to do a bunch of fire-and-forget operations.

In my controller I send the model instance to the post-processor:

import _root_.com.eaio.uuid.UUID
import akka.actor.Props
// ... skip a bunch of code
play.api.libs.concurrent.Akka.system.actorOf(
    Props[MySomethingPostprocessorActor],
    name = "somethingActor"+new UUID().toString()
) ! something

The MySomethingPostprocessorActor actor looks like this:

class MySomethingPostprocessorActor extends Actor with ActorLogging {

    def receive = {
        case Something(thing, alpha, beta) => try {
                play.api.libs.concurrent.Akka.system.actorOf(
                    Props[MongoActor],
                    name = "mongoActor"+new UUID().toString()
                ) ! Something(thing, alpha, beta)
                play.api.libs.concurrent.Akka.system.actorOf(
                    Props[PubsubActor],
                    name = "pubsubActor"+new UUID().toString()
                ) ! Something(thing, alpha, beta)
                // ... and so forth
        } catch {
            case e => {
                log.error("MySomethingPostprocessorActor error=[{}]", e)
            }
        }
    }
}

So, here's what I'm not sure about:

I know Actor factories are discouraged as per the warning on this page. My remedy for this is to name each actor instance with a unique string provided by UUID, to get around the your-actor-is-not-unique errors:

play.core.ActionInvoker$$anonfun$receive$1$$anon$1:
    Execution exception [[InvalidActorNameException:
        actor name somethingActor is not unique!]]

Is there a better way to do the above, i.e. instead of giving everything a unique name? All examples in the Akka docs I encountered give actors a static name, which is a bit misleading.

(any other comments are welcome too, e.g. the if the bundling pattern I use is frowned upon, etc)

Upvotes: 3

Views: 1248

Answers (1)

fedenusy
fedenusy

Reputation: 274

As far as I'm aware the name paramater is optional.

This may or may not be the case with Akka + Play (haven't checked). When working with standalone actor systems though, you usually only name an actor when you need that reference for later.

From the sounds of it you're tossing out these instances after using them, so you could probably skip the naming step.

Better yet, you could probably save the overhead of creating each actor instance by just wrapping your operations in Futures and using callbacks if need be: http://doc.akka.io/docs/akka/2.0.3/scala/futures.html

Upvotes: 1

Related Questions