Skip to content

Instantly share code, notes, and snippets.

@j14159
Created July 27, 2014 23:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j14159/ca191b61a73382316f9c to your computer and use it in GitHub Desktop.
Save j14159/ca191b61a73382316f9c to your computer and use it in GitHub Desktop.
trait PersonClient {
// supply a router with a pool of PersonDao:
val personPool: ActorRef
// how long should we wait for a response from PersonDao:
val timeoutInMillis: Long
implicit val timeout = Timeout(timeoutInMillis millis)
def addPerson(p: Person): Future[Int] =
(personPool ? p).mapTo[Int]
def personById(id: Long): Future[Person] =
(personPool ? PersonById).mapTo[Person]
}
@muuki88
Copy link

muuki88 commented Sep 16, 2014

Nice. I had some ideas on this kind of architecure here. Currently I'm trying this idea and found some edges to think about

Timeouts

Should I use a global timeout like you, or add it as an implicit parameter for each method, so the caller can decide

ActorRef or ActorSelection

ActorRef or ActorSelection? When I'm using a cluster, I configure cluster aware routers and just implement like a "dummy actor"

class YourServiceActor extends Actor {

  // define the cluster in the config
  val backend = context.actorOf(FromConfig.props, "yourServiceRouter")

  def receive = {
     // just forward to the cluster aware router
     case msg: YourServiceApi => backend forward msg
  }

}

However if you want to reuse a local service directly an ActorSelection maybe
easier (not 100% sure about that)

Direct Usage of API

If I build services on top of other services, you can use the message api directly to have full control of dispatchers/flow-control/async-stuff
E.g

def receive = {
    case GetItem(id) => getItem(id) pipeTo sender
}

def getItem(id: Int): Future[Item] = {
  val queryFuture: Future[Item] = DatabaseService.query( { implicit c: java.sql.Connection =>
      // load your stuff
      Item()
  })
  queryFuture
}

// or --------------------

def receive = {
    case GetItem(id) => DatabaseService.actor() forward Query({ implicit c: java.sql.Connection =>
         // your query
         Item()
   })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment