java - 如何从异步 Play 操作返回结果

标签 java asynchronous playframework-2.0

我尝试使用 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());
}

现在我想在将数据返回给客户端之前检查一些值:(例如一些 header 值)

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。考虑到这一点,编写异步代码就变得非常容易且令人愉快!

最佳答案

您需要将结果包装在 CompletionStage 中,就像

} Else {
   return CompletableFuture.completedFuture(ok("value is Not some Data ..."))
}

关于java - 如何从异步 Play 操作返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47221331/

相关文章:

java - ANTLR - 左递归去除辅助

javascript - while 循环中的异步方法与 Graph API 分页

playframework-2.0 - 如何在 Play Framework 中将时区设置为 UTC

scala - 如何在Scala Play框架中以JSON形式返回模型查询结果

java - 如何使用单个 JOptionPane.showMessageDialog() 语句显示多个输出?

java - 使用 Tomcat 进行调试

java - 模板处理——查找字符串中的变量引用

java - Java中的非阻塞(异步)DNS解析

javascript - js : promises inside a while- true loop

eclipse - 在从 Eclipse 执行的 Play 2.0 应用程序的 (Selenium) JUnit 测试中找不到静态资源