Play 2.6 异步处理结果

异步处理结果

英文原文
https://playframework.com/documentation/2.6.x/JavaAsync

创建异步的controller

Play是一个自底向上的异步框架,play处理所有的request都是异步、非阻塞的。

默认的方式是使用异步的controller。换句话说,contrller中的应用代码需要避免阻塞,i.e.不能等待某一个操作。场景的阻塞操作有JDBC调用、streaming API、HTTP请求和耗时计算。

虽然可以通过增加线程池中线程的数量来让阻塞的controller处理更多的请求。还是通过以下建议使controller异步来保持程序的可靠性和可扩展性。

创建非阻塞的action

在Play的机制中,action需要尽可能的块,非阻塞。在计算未完成时,可以返回promise of a result!

Java8提供了一个新的APICompletionStage。一个CompletionStage<Result>实例最终会返回一个Result类型的对象。通过使用CompletionStage<Result>代替普通的Result,action可以非阻塞的返回,Play最终会处理返回的结果。

如何创建CompletionStage

在创建CompletionStage<Result>前,我们需要另外一项保证:保证会给到我们计算中实际需要的值。

CompletionStage<Double> promiseOfPIValue = computePIAsynchronously();
// Runs in same thread
CompletionStage<Result> promiseOfResult = promiseOfPIValue.thenApply(pi ->
                ok("PI value computed: " + pi)
);

Play的异步API会返回一个CompletionStage实例。比如通过play.libs.WS调用外部web服务,或者使用Akka进行异步计算。

这个例子中,CompletionStage.thenApply在进行当前阶段的计算时与之前的任务在同一个线程中执行。This is fine when you have a small amount of CPU bound logic with no blocking.

若要使用异步计算,可以调用CompletionStage.supplyAsync()方法

// import static java.util.concurrent.CompletableFuture.supplyAsync;
// creates new task
CompletionStage<Integer> promiseOfInt = CompletableFuture.supplyAsync(() ->
        intensiveComputation());

使用supplyAsync创建的新任务会被安置在fork join pool中,而且可能会被不同的线程调用,虽然这里使用的是默认的执行器,也可以指定一个执行器。

注意:只有*Async结尾的方法才是异步执行的

使用HttpExecutionContext

在Action中使用Java CompletionStage就必须显示地为HTTP执行环境指明一个executor,来保证HTTP.Context保存在当前域中。如果没有提供http执行环境,在调用request()等依赖HTTP.Context的方法时会得到一个”There is no HTTP Context available from here”的错误。

可以通过注入的方式提供一个play.libs.concurrent.HttpExecutionContext的实例。

import play.libs.concurrent.HttpExecutionContext;
import play.mvc.*;

import javax.inject.Inject;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;

public class MyController extends Controller {

    private HttpExecutionContext httpExecutionContext;

    @Inject
    public MyController(HttpExecutionContext ec) {
        this.httpExecutionContext = ec;
    }

    public CompletionStage<Result> index() {
        // Use a different task with explicit EC
        return calculateResponse().thenApplyAsync(answer -> {
            // uses Http.Context
            ctx().flash().put("info", "Response updated!");
            return ok("answer was " + answer);
        }, httpExecutionContext.current());
    }

    private static CompletionStage<String> calculateResponse() {
        return CompletableFuture.completedFuture("42");
    }
}

请在Java thread locals获取更多Java thread locals与HttpExecutionContext的细节。

使用CustomExecutionContext和HttpExecution

使用CompletionStage或者HttpExecutionContext才仅仅完成了一半。目前仍然在使用Play默认的执行上下文,如果调用了一个像JDBC这样的阻塞API,我们需要让当前的ExecutionStage移出Play的线程池,在一个不同的executor中执行。可以通过创建一个拥有 custom dispatcherplay.libs.concurrent.CustomExecutionContext子类来实现。

定义一个执行上下文

public class MyExecutionContext extends CustomExecutionContext {

    @Inject
    public MyExecutionContext(ActorSystem actorSystem) {
        // uses a custom thread pool defined in application.conf
        super(actorSystem, "my.dispatcher");
    }

}

然后需要在application.conf中定义一个custom dispatcher,详见Akka的文档

akka {

my.dispatcher {
  type = Dispatcher
  executor = "thread-pool-executor"
  thread-pool-executor {
    fixed-pool-size = 32
  }
  throughput = 1
}


}

(不是很了解application.conf的读取方式,经测试my.dispatcher不妨在akka放在根目录下也能正常执行)在拥有自己的dispatcher之后,可以显示的添加executor然后使用HttpException.fromThread进行封装

public class Application extends Controller {

    private MyExecutionContext myExecutionContext;

    @Inject
    public Application(MyExecutionContext myExecutionContext) {
        this.myExecutionContext = myExecutionContext;
    }

    public CompletionStage<Result> index() {
        // Wrap an existing thread pool, using the context from the current thread
        Executor myEc = HttpExecution.fromThread((Executor) myExecutionContext);
        return supplyAsync(() -> intensiveComputation(), myEc)
                .thenApplyAsync(i -> ok("Got result: " + i), myEc);
    }

    public int intensiveComputation() { return 2;}
}
即使使用了CompletionStage也不可能将同步的IO转换为异步的IO。如果不能避免使用某些阻塞方法(这些方法在某些时间点总会执行,然后某些线程就会被阻塞),除了将操作封装在CompletionStage,还需要添加一个拥有足够线程的隔离的执行上下文来处理并发。可以在[这里](https://playframework.com/documentation/2.6.x/ThreadPools)查看更多与Play线程池有关的内容,也可以在[这里](https://playframework.com/download#examples)下载一个与数据库相关的例子

action默认都是异步的

Play中的action都是异步的,比如下面的例子,返回的Result在内部包含了一个承诺

public Result index() {
    return ok("Got request " + request() + "!");
}
无论代码中返回的是Result还是CompletionStage,这两种返回方式在Play的内部处理都是一样的,Action只有异步这一种类型。返回CompletionStage是一种写非阻塞代码的技术。

处理超时

在非阻塞的超时中,可以用play.libs.concurrent.Futures.timeout来封装一个CompletionStage

class MyClass {

    private final Futures futures;
    private final Executor customExecutor = ForkJoinPool.commonPool();

    @Inject
    public MyClass(Futures futures) {
        this.futures = futures;
    }

    CompletionStage<Double> callWithOneSecondTimeout() {
        return futures.timeout(computePIAsynchronously(), Duration.ofSeconds(1));
    }

    public CompletionStage<String> delayedResult() {
        long start = System.currentTimeMillis();
        return futures.delayed(() -> CompletableFuture.supplyAsync(() -> {
            long end = System.currentTimeMillis();
            long seconds = end - start;
            return "rendered after " + seconds + " seconds";
        }, customExecutor), Duration.of(3, SECONDS));
    }

}
超时与取消并不相同, – 超时的情况下计算任然会继续,尽管结果不会返回
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
[强烈推荐, 文档不多, 很快就可以看完, 看完了, 就会使用play了] 目录 MVC应用程序模型 - 7 - app/controllers - 8 - app/models - 8 - app/views - 8 - 请求生命周期 - 8 - 标准应用程序布局layout - 9 - app目录 - 9 - public目录 - 10 - conf目录 - 10 - lib目录 - 11 - 开发生命周期 - 11 - 连接到java调试器 - 12 - 类增强Enhancement - 13 - 02.HTTP路由 - 13 - 关于REST - 14 - routes文件语法 - 14 - HTTP方法 - 15 - URI范示 Pattern - 15 - Java调用定义 - 17 - 把404当作action来用 - 17 - 指派静态参数 - 17 - 变量和脚本 - 18 - 路由优先级 - 18 - 服务器静态资源 - 18 - staticDir: mapping - 18 - staticFile: mapping - 19 - URL 编码 - 19 - 反转路由:用于生成某些URL - 19 - 设置内容风格(CSS) - 20 - HTTP 内容协商 negotiation - 21 - 从http headers开始设置内容类型 - 21 - 定制格式 - 22 - 03.控制器 - 23 - 控制器概览 - 23 - 获取http参数 - 24 - 使用params map - 25 - 还可以从action方法签名实现转换 - 25 - 高级HTTP Java绑定 - 26 - 简单类型 - 26 - Date类型 - 26 - Calendar日历 - 27 - File - 27 - 支持类型的数组或集合 - 28 - POJO对象绑定 - 29 - JPA 对象绑定 - 30 - 定制绑定 - 30 - @play.data.binding.As - 30 - @play.data.binding.NoBinding - 31 - play.data.binding.TypeBinder - 31 - @play.data.binding.Global - 32 - 结果类型 - 32 - 返回一些文本类型的内容 - 33 - 返回一个JSON字符串 - 33 - 返回一个XML字符串 - 34 - 返回二进制内容 - 34 - 作为附件下载文件 - 34 - 执行一个模板 - 35 - 跳转到其他URL - 36 - Action链 - 36 - 定制web编码 - 37 - 拦截器 - 38 - @Before - 38 - @After - 39 - @Catch - 40 - @Finally - 41 - 控制器继承 - 42 - 使用@With注释添加更多的拦截器 - 42 - Because Java does not allow multiple inheritance, it can be very limiting to rely on the Controller hierarchy to apply interceptors. But you can define some interceptors in a totally different class, and link them with any controller using the @With annotation.由于java不允许多继承,通过控制器继承特点来应用拦截器就受到极大的限制。但是我们可以在一个完全不同的类里定义一些拦截器,然后在任何控制器里使用@With注释来链接他们。 - 42 - Session和Flash作用域 - 42 - 04.模板引擎 - 43 - 模板语法 - 43 - Expressions: ${…} - 44 - Template decorators : #{extends /} and #{doLayout /} - 44 - Tags: #{tagName /} - 45 - Actions: @{…} or @@{…} - 46 - Messages: &{…} - 46 - Comment: *{…}* - 46 - Scripts: %{…}% - 46 - Template inheritance继承 - 47 - 定制模板标签 - 48 - 检索tag参数 - 48 - 调用标签体 - 48 - 格式化特定标签 - 49 - 定制java标签 - 49 - 标签命名空间 - 50 - 在模板里的Java对象扩展 - 51 - 创建定制扩展 - 52 - 模板里可以使用的保留对象 - 52 - 05.用play验证http数据 - 53 - 在play里验证如何进行的? - 53 - 验证的错误消息 - 54 - Localised validation messages 局部验证消息 - 55 - 验证消息参数 - 55 - 定制局部验证消息 - 56 - 定制teral(非局部)验证消息 - 57 - 在模板里显示验证错误消息 - 57 - 验证注释 - 60 - 验证复杂对象 - 60 - 内建验证 - 61 - 使用@CheckWith定制验证 - 61 - 定制注释 - 62 - 06.域对象模型 - 64 - 属性模仿 - 65 - 设置数据库来持久化模型对象 - 68 - 用hibernate持久化对象模型 - 69 - 保持模型stateless - 70 - 07.JPA持久化 - 70 - 启动JPA实体管理器 - 70 - 获取JPA实体管理器 - 70 - 事务管理 - 71 - play.db.jpa.Model支持类 - 71 - 为GenreicModel定制id映射 - 72 - Finding对象 - 72 - Find by ID - 72 - Find all - 73 - 使用简单查询进行查找 - 73 - 使用JPQL 查询进行查找 - 74 - Counting统计对象 - 74 - 用play.db.jpa.Blob存储上传文件 - 74 - 强制保存 - 75 - 更多公共类型generic typing问题 - 77 - 08.Play.libs库包 - 78 - 用XPath解析XML - 78 - Web Service client - 79 - Functional programming with Java功能扩展? - 79 - Option<T>, Some<T> and None<T> - 80 - Tuple<A, B> - 80 - Pattern Matching模式匹配 - 81 - Promises - 81 - OAuth - 82 - OAuth 1.0 - 82 - OAuth 2.0 - 83 - OpenID - 84 - 09.异步Jobs - 86 - 引导程序任务Bootstrap jobs - 87 - 预定义任务Scheduled jobs - 87 - 触发任务job - 88 - 停止应用程序 - 89 - 10.在HTTP下进行异步编程 - 89 - 暂停http请求 - 89 - Continuations - 90 - 回调Callbacks - 91 - HTTP response流 streaming - 92 - 使用WebSockets - 92 - 11.在play框架里使用Ajax - 94 - 通过jsAction标签使用jQuery - 95 - 12. Internationalization国际化支持 - 96 - 仅使用 UTF-8! - 96 - 国际化你的信息 - 96 - 通过应用程序定义支持的语言 - 96 - 依照你的区域定义日期格式 - 97 - 找回区域信息 - 97 - Message arguments - 97 - 模板输出 - 98 - 多参数 - 98 - 立即数Argument indices - 98 - 13.使用cache - 99 - The cache API - 99 - 不要把Session当成缓存! - 101 - 配置mcached - 101 - 14.发送e-mail - 102 - Mail 和MVC 集成 - 102 - text/html e-mail - 103 - text/plain e-mail - 104 - text/html e-mail with text/plain alternative - 104 - 在应用程序里链接到邮件 - 104 - SMTP配置 - 105 - 使用 Gmail - 105 - 15.测试应用程序 - 105 - 书写测试程序 - 105 - 单元测试 - 106 - 功能性测试 - 106 - Selenium test用例测试 - 107 - Fixtures固定值 - 108 - 运行测试 - 110 - 陆续集成,并自动运行测试 - 111 - 16.安全指南 - 112 - Sessions - 112 - 守住你的安全…安全 - 112 - 不要存储关键性的数据 - 112 - 跨站点脚本攻击 - 112 - SQL注入 - 113 - 跨站点请求伪造 - 114 - 17.Play模块和模块仓库 - 115 - 什么是模块? - 115 - 如何从一个应用程序里加载模块 - 115 - 从模块加载默认的routes - 115 - 为模块增加文档说明 - 115 - 使用模块仓库 - 116 - 贡献新模块到模块仓库里 - 117 - 先决条件 - 117 - 模块注册 - 117 - 发布你的模块 - 118 - 18.依赖管理 - 118 - 依赖格式 - 119 - 动态版本 - 119 - dependencies.yml - 119 - ‘play dependencies’命令 - 120 - 透明依赖 - 121 - 保持lib/和modules/目录同步 - 122 - 冲突判定Conflict resolution - 123 - 增加要的仓库 - 124 - Maven仓库 - 125 - 本地仓库 - 125 - 定制ivy设置(Apache ivy:项目依赖管理工具) - 126 - 清除Ivy缓存 - 127 - 19.管理数据库变化Evolution - 128 - Evolutions脚本 - 128 - 同步同时发生的改变 - 130 - 数据不一致状态 - 133 - Evolutions 命令 - 136 - 20.日志配置 - 139 - 对应用程序进行日志 - 139 - 配置日志级别 - 140 - 生产配置 - 140 - 21.管理多环境下的application.conf - 140 - 框架id(framework ID) - 141 - 从命令行设置框架id - 142 - 22.生产部署 - 142 - application.conf - 142 - 设置框架为prod模式: - 142 - 定义一个真实的数据库: - 143 - 禁止JPA的自动结构更新: - 143 - 定义一个安全的secret key: - 143 - 日志配置 - 143 - 前端http服务器(Front-end HTTP server) - 144 - 部署到lighttpd服务器的设置 - 144 - 部署到Apache服务器的设置 - 145 - Apache作为前端代理服务器,可以允许透明更新你的应用程序 - 145 - 高级代理设置 - 146 - HTTPS配置 - 147 - 不依赖Python进行部署 - 148 - 23.部署选择 - 148 - 独立Play应用程序 - 149 - Java EE应用服务器 - 149 - 支持应用服务器 - 149 - 部署 - 150 - 数据源 - 150 - 定制web.xml - 151 - 基于云的主机Cloud-based hosting - 151 - AWS Elastic Beanstalk - 152 - CloudBees - 152 - Cloud Foundry - 152 - Google App Engine (GAE) - 152 - Heroku - 152 - playapps.net - 153 -
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值