简体   繁体   中英

Is Play Framework suitable for asynchronous background processing?

I'm going to build a web application that's going to host urban games.

A user visits my website, clicks "Start game" and starts receiving some SMS messages when gets to some location and has to answer them to get points.

Is Play suitable for this kind of application? After clicking the "start game" button some logic has to go on its own course. How would I handle checking geolocation of the players (I have API for that) parallely? I would like to ping the player every ~5 sec. and do some logic. The user of course has to be able to use the web application at the same time as it's processing his location, assigning points, sending and receiving messages etc.

So to sum up: I want an application written in Play that starts a separate thread for a game after clicking "start game" and other users are able to view their data (statisctics etc.), while the threads work their way with the game logic.

I found something like jobs but they are documented for version 1.2. After some reading it turned out that Akka is the recommended one now but it uses and actor model.

Is Play + Akka a good choice for my project?

Absolutely. It is very easy to set up computations in a separate ThreadPool (also referred to as ExecutionContext) with the Play Framework. You may want to read up on the documentation here , but in a nutshell you'll be wanting to do something like this in your Application.scala controller file (note this example uses Scala):

  // Async Action that's triggered when a user clicks "Start Game".
  // Runs logic in separate gameLogicContext thread pool and asynchronously returns a response without blocking of Play's default thread pool.
  def startGame = Action.async { implicit request =>

    Future {

      // ... your game logic here. This will be run in gameLogicContext

      Ok("Game started in separate thread pool") // http response

    }(Contexts.gameLogicContext) // the thread pool the future should run in.

  }

And then you will set up a separate gameLogicContext thread pool within your application.conf file:

play {
  akka {
    actor {
      game-logic-context = {
        fork-join-executor {
          parallelism-min = 300
          parallelism-max = 300 // thread pool with 300 threads
        }
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM