DbOperation.scala 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. package utils
  2. import akka.actor.ActorSystem
  3. import java.sql.Connection
  4. import java.util.concurrent._
  5. import javax.inject.{Singleton, Inject}
  6. import play.api.db.Database
  7. import play.api.libs.concurrent.CustomExecutionContext
  8. import play.api.Configuration
  9. import scala.concurrent._
  10. import scala.concurrent.Future
  11. @Singleton
  12. class DbOperation @Inject() (protected val db: Database,
  13. configuration: Configuration, dbEc: DatabaseExecutionContext) {
  14. /**
  15. * Run a DB operation in the DB context.
  16. */
  17. def asyncDbOp[T](op: Connection => T): Future[T] = {
  18. // If the thread-pool queue used by the database grows too large then our server
  19. // is probably struggling, and we should start dropping requests. If we don't
  20. // then we'll just slow everything down and it will fail anyway. Better to fail
  21. // quickly rather than slowly. Set the max size of our queue something above the
  22. // number of concurrent connections that we expect to be handling.
  23. Future {
  24. db.withConnection { connection => op(connection) }
  25. }(dbEc)
  26. }
  27. }
  28. class DatabaseExecutionContext @Inject()(actorSystem: ActorSystem)
  29. extends CustomExecutionContext(actorSystem, "database.dispatcher")