AsyncController.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package controllers;
  2. import akka.actor.ActorSystem;
  3. import javax.inject.*;
  4. import akka.actor.Scheduler;
  5. import play.*;
  6. import play.mvc.*;
  7. import java.util.concurrent.Executor;
  8. import java.util.concurrent.CompletableFuture;
  9. import java.util.concurrent.CompletionStage;
  10. import java.util.concurrent.TimeUnit;
  11. import scala.concurrent.ExecutionContext;
  12. import scala.concurrent.duration.Duration;
  13. import scala.concurrent.ExecutionContextExecutor;
  14. /**
  15. * This controller contains an action that demonstrates how to write
  16. * simple asynchronous code in a controller. It uses a timer to
  17. * asynchronously delay sending a response for 1 second.
  18. */
  19. @Singleton
  20. public class AsyncController extends Controller {
  21. private final ActorSystem actorSystem;
  22. private final ExecutionContextExecutor exec;
  23. /**
  24. * @param actorSystem We need the {@link ActorSystem}'s
  25. * {@link Scheduler} to run code after a delay.
  26. * @param exec We need a Java {@link Executor} to apply the result
  27. * of the {@link CompletableFuture} and a Scala
  28. * {@link ExecutionContext} so we can use the Akka {@link Scheduler}.
  29. * An {@link ExecutionContextExecutor} implements both interfaces.
  30. */
  31. @Inject
  32. public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) {
  33. this.actorSystem = actorSystem;
  34. this.exec = exec;
  35. }
  36. /**
  37. * An action that returns a plain text message after a delay
  38. * of 1 second.
  39. *
  40. * The configuration in the <code>routes</code> file means that this method
  41. * will be called when the application receives a <code>GET</code> request with
  42. * a path of <code>/message</code>.
  43. */
  44. public CompletionStage<Result> message() {
  45. return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec);
  46. }
  47. private CompletionStage<String> getFutureMessage(long time, TimeUnit timeUnit) {
  48. CompletableFuture<String> future = new CompletableFuture<>();
  49. actorSystem.scheduler().scheduleOnce(
  50. Duration.create(time, timeUnit),
  51. () -> future.complete("Hi!"),
  52. exec
  53. );
  54. return future;
  55. }
  56. }