Employee-Self-Service: Reactive and Non-Blocking Database Access using Play Framework and Anorm – (Part-3)

Last week, We have added Reactive and Non-Blocking behaviour in Employee-Self-Service  application.

Now we have implemented Database Access as Reactive and Non-Blocking:

  • Before

def list() = Action.async { implicit request =>
   Employee.list match {
    case Right(data) => Promise.timeout(Ok(html.list(data)), 1 seconds)
    case Left(error) => Promise.timeout(Ok(html.list(Nil)), 1 seconds)
   }
}
  • After

def list() = Action.async { implicit request =>
 val futureEmpList = scala.concurrent.Future { Employee.list }
 val timeoutFuture = Promise.timeout("Oops", 10.second)
 Future.firstCompletedOf(Seq(futureEmpList, timeoutFuture)).map {
   case data: List[Employee] => Ok(html.list(data))
   case t: String =>
      Logger.error("Problem found in employee list process")
      InternalServerError(t)
   }
}

Details: If we want to make a web application request as Reactive and Non-Blocking Database Access than we need to do the following things:

  • Returning futures

While we were using the Action.apply builder methods to build actions until now,  to send an asynchronous result, we need to use the Action.async buider method:

import play.api.libs.concurrent.Execution.Implicits.defaultContext

def index =Action.async {
    val futureData = scala.concurrent.Future{ DATABASE_CALL}
    futureData.map(data=>Ok("Got Data: "+ data))
}
  • Handling time-outs properly

It is often useful to handle time-outs properly, to avoid having the web browser block and wait if something goes wrong. You can easily compose a promise with a promise timeout to handle these cases:

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.concurrent.Promise
import scala.concurrent.duration._

def list = Action.async {
     val futureData = scala.concurrent.Future{ DATABASE_CALL}
     val timeoutFuture = Promise.timeout("Oops got error",10.second)
     Future.firstCompletedOf(Seq(futureData, timeoutFuture)).map {
        case data: CASE_CLASS => Ok("Got data: "+ data)
        case error: String=> InternalServerError(error)
     }
}

Check the application and the code base on bellow links:

The live application is currently hosted at : http://employee-self-service.herokuapp.com/
The Github code for the project is at : https://github.com/knoldus/Employee-Self-Service

This is the third edition of this application. If you have any changes then feel free to send in pull requests and we would do the merges 🙂 Stay tuned.

Previous blogs related to this application:

1. http://blog.knoldus.com/2014/03/24/employee-self-service-building-reactive-play-application-with-anorm-sql-data-access/

2. http://blog.knoldus.com/2014/03/31/employee-self-service-2/

1 thought on “Employee-Self-Service: Reactive and Non-Blocking Database Access using Play Framework and Anorm – (Part-3)

Leave a Reply

%d bloggers like this: