Blankman
Blankman

Reputation: 266988

How do you handle multiple execution contexts for mysql, redis and memcache?

If I am making 3 different types of requests in a single Action, how should I handle things if they all have their own execution contexts, is there a best practise for this type of scenerio?

In an action I need to do the following:

  1. Make db calls using slick to mysql
  2. Make redis calls
  3. Make memcache calls

So say my action looks like this where I have 3 different execution contexts, please correct me where I have erred:

def userProfile = Action.async {
  Future {
    // db
  }(Contexts.myDbEC)

  Future {
    // redis calls
  }(Contexts.myRedisEC)

  Future {
    // memcache calls
  }(Contexts.myMemcacheEC)

}
  1. Is it correct that I have to use Action.asynch in this case? Why is that?
  2. What if I need the result of one execution context with the other, how will I handle this?
  3. How will I combine the results when the Future code executes in the block, do I have to define my variables outside of the future calls or is there a way to get a return value?

Upvotes: 1

Views: 132

Answers (1)

Vikas Pandya
Vikas Pandya

Reputation: 1988

Usage of Action.async is correct if you wanted to make your Action async which then should return a Future.

For your second question assuming you want to retrieve result of one future and combine with another one? - you can compose futures using flatMap or foreach.

Going with your example you can collect future results and use for comprehension to collect the result.

val future1 = future{ //db call }
val future2 = future{ //redis call}
val future3 = future{//memcache call}

val res = for{
            r1 <- future1
            r2 <- future2
            r3 <- future3
          } yield(r1+r2+r3)

note: it's important to run those futures outside for comprehension as above to run them in parallel. If you did following then they will run sequentially.

val res = for{
            r1 <- future{//db call}
            r2 <- future{//redis call}
            r3 <- future{//memcache call}
          }

Upvotes: 1

Related Questions