Application.scala 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package controllers
  2. import play.api.Play.current
  3. import play.api.mvc._
  4. import play.api.libs.json.Json
  5. import java.util.concurrent._
  6. import scala.concurrent._
  7. import models._
  8. import utils._
  9. import scala.concurrent.Future
  10. import play.api.libs.concurrent.Execution.Implicits._
  11. import play.core.NamedThreadFactory
  12. object Application extends Controller {
  13. private val TestDatabaseRows = 10000
  14. private val partitionCount = current.configuration.getInt("db.default.partitionCount").getOrElse(2)
  15. private val maxConnections =
  16. partitionCount * current.configuration.getInt("db.default.maxConnectionsPerPartition").getOrElse(5)
  17. private val minConnections =
  18. partitionCount * current.configuration.getInt("db.default.minConnectionsPerPartition").getOrElse(5)
  19. private val tpe = new ThreadPoolExecutor(minConnections, maxConnections,
  20. 0L, TimeUnit.MILLISECONDS,
  21. new LinkedBlockingQueue[Runnable](),
  22. new NamedThreadFactory("dbEc"))
  23. private val dbEc = ExecutionContext.fromExecutorService(tpe)
  24. // A predicate for checking our ability to service database requests is determined by ensuring that the request
  25. // queue doesn't fill up beyond a certain threshold. For convenience we use the max number of connections
  26. // to determine this threshold. It is a rough check as we don't know how many queries we're going
  27. // to make or what other threads are running in parallel etc. Nevertheless, the check is adequate in order to
  28. // throttle the acceptance of requests to the size of the pool.
  29. def isDbAvailable: Boolean = (tpe.getQueue.size() < maxConnections)
  30. def json() = Action {
  31. Ok(Json.obj("message" -> "Hello World!"))
  32. }
  33. def db(queries: Int) = PredicatedAction(isDbAvailable, ServiceUnavailable) {
  34. Action {
  35. Async {
  36. val random = ThreadLocalRandom.current()
  37. val worlds = Future.sequence((for {
  38. _ <- 1 to queries
  39. } yield Future(World.findById(random.nextInt(TestDatabaseRows) + 1))(dbEc)
  40. ).toList)
  41. worlds map {
  42. w => Ok(Json.toJson(w))
  43. }
  44. }
  45. }
  46. }
  47. }