java - 如何从 Java Play 框架中的动作返回结果?
问题描述
我所有的控制器都使用CheckDowntimeAction
我创建的这个。
@Singleton
@With(CheckDowntimeAction.class)
public class MyController extends Controller {
}
正如预期的那样,在每次请求时,都会CheckDowntimeAction
打印“我在这里!”。但是我如何在 中中止,CheckDowntimeAction
以便如果站点关闭,我返回我自己在 中创建的结果CheckDowntimeAction
?
public class CheckDowntimeAction extends play.mvc.Action.Simple {
@Override
public CompletionStage<Result> call(Http.Request req) {
logger.info("I'm here!");
// just move along, nothing to see here
return delegate.call(req);
}
}
这可行,但它会在运行完成后打印停机时间结果MyController
。我希望它在控制器完成之前运行。
public class CheckDowntimeAction extends play.mvc.Action.Simple {
@Override
public CompletionStage<Result> call(Http.Request req) {
if (downtime) {
Result r = badRequest("Site is down");
// before Play 2.7, this would have been:
// return F.Promise.pure(badRequest(r));
return delegate.call(req).thenApply(result -> r);
}
// just move along, nothing to see here
return delegate.call(req);
}
}
请注意,这是使用使用请求而不是上下文的 Java Play 2.7,并且 F.Promise 不再可用。见https://www.playframework.com/documentation/2.7.x/JavaHttpContextMigration27
解决方案
根据https://www.playframework.com/documentation/2.5.1/api/java/play/libs/F.Promise.html F.Promise
中的文档已弃用,它说要CompletableFuture.completedFuture
改用。Play 2.7 中的变化是它F.Promise
最终被完全删除。
我相信正确的 Play 2.7 方式是这样的:return CompletableFuture.completedFuture(r);
推荐阅读
- sql - 如何根据我的选择语句中的其他 3 列创建新列
- angularjs - 将服务的值保存在变量中
- mysql - 无法使用联合引擎 mysql 在 ipv6 上连接远程服务器
- apache - 在 > 1024 的端口上运行 apache 容器
- android-recyclerview - 拖放后如何将项目位置存储在 RecyclerView 中
- python - python中一个大列表的总和
- python - 查询关于时区的一天
- sql-server - 将 Microsoft SQL Server 中的文件表链接到 Microsoft Access 2016 中的表
- node.js - Elasticsearch nodejs检查队列是否已满
- html - 具有多个 colspan 的两个表头