我尝试使用play Framework开发一个简单的REST-API,并坚持以下内容:
我有2个方法:获取一些数据库数据
public CompletionStage<PagedList<Computer>> page(int page, int pageSize, String sortBy, String order, String filter) {
return supplyAsync(() -> {
return ebeanServer.find(Computer.class).where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.fetch("company")
.setFirstRow(page * pageSize)
.setMaxRows(pageSize)
.findPagedList();
} , executionContext);
}
第二个是:返回数据
public CompletionStage<Result> list(int page, String sortBy, String order, String filter) {
// Run a db operation in another thread (using DatabaseExecutionContext)
return computerRepository.page(page, 10, sortBy, order, filter).thenApplyAsync(list -> {
// This is the HTTP rendering thread context
return ok(views.html.list.render(list, sortBy, order, filter));
}, httpExecutionContext.current());
}
现在我想在将数据返回给客户端之前检查一些值:(例如某些标题值)
public CompletionStage<Result> list(int page, String sortBy, String order, String filter) {
If(x=„somedata“){
// Run a db operation in another thread (using DatabaseExecutionContext)
return computerRepository.page(page, 10, sortBy, order, filter).thenApplyAsync(list -> {
// This is the HTTP rendering thread context
return ok(views.html.list.render(list, sortBy, order, filter));
}, httpExecutionContext.current());
} Else {
Return ok(„value is Not some Data ...“)
}
}
问题是,我无法返回一个简单的结果......最好的方法是什么?也许在异步方法中扭曲结果?这是一个好习惯吗?
该示例来自此github网站:https://github.com/playframework/play-java-ebean-example
解决方案: 使用Andriy Kuba的awnser,我再次阅读了CompletableFuture和CompletionStage的javadoc。它接缝是这样做的正确方法!对于想要在异步中使用Play框架的所有人(这非常重要),请查看https://github.com/playframework/play-java-ebean-example处的示例并阅读CompletionStage(https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html)和CompletableFuture(https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html)的javadoc。考虑到这一点,编写异步代码非常容易和快乐!
答案 0 :(得分:1)
您需要将结果包装在CompletionStage
中,就像
} Else {
return CompletableFuture.completedFuture(ok("value is Not some Data ..."))
}