【问题标题】:How to send a asynchronous response in an Undertow HttpHandler如何在 Undertow HttpHandler 中发送异步响应
【发布时间】:2014-10-02 00:22:12
【问题描述】:

我正在寻找一个示例,该示例说明您如何在 HttpHandler 中异步编写响应?问题是当 HttpServerExchange.endExchange 被调用时,响应被刷新。我的示例 HttpHandler 使用 Scala 的 rx-java 库。

class MyHandler() extends HttpHandler {
  override def handleRequest(exchange: HttpServerExchange) = {
    val observable = Observable.items(List(1, 2, 3)) // simplistic not long running
    observable.map {
      // this is run async
      myList => exchange.getResponseSender.send(myList.toString)
    }
  }
}

【问题讨论】:

    标签: java scala jboss nonblocking undertow


    【解决方案1】:

    如果您调用 dispatch() 方法,则在调用堆栈返回时交换不会结束,但是在这种情况下即使这样也很不礼貌。

    你可能想要这样的东西:

    exchange.dispatch(SameThreadExecutor.INSTANCE, () -> {
    observable.map {
      // this is run async
      myList => exchange.getResponseSender.send(myList.toString)
    }}
    

    基本上这将等到调用堆栈返回后再运行异步任务,这意味着没有竞争的可能性。由于交换不是线程安全的,这种方法确保一次只能运行一个线程。

    【讨论】:

    • 你的意思是在我的handleRequest中的代码之前是这样的:undertow.io/documentation/core/undertow-request-lifecycle.html
    • 如果没有一些额外的代码,这似乎不起作用。我看到Connectors.executeRootHandler() 处理调度,当不是resumed 时它结束exchange。因此,如果在代码到达 if (!resumed) {exchange.endExchange();} 之前未发出 observable 调用失败并出现 response has already been sent...
    • 我已将处理程序的调度替换为仅在 handler.handleRequest(exchange); 上执行的自定义可运行对象的调度,这很有效,但很难说我是否遗漏了 exchange 生命周期中的重要内容。
    • undertow-request-lifecycle 的链接坏了,所以有工作链接:undertow.io/undertow-docs/undertow-docs-1.4.0/…
    • 在我看来,这需要清楚地记录下来,因为异步编写响应的能力是使用非阻塞的基础http服务器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    相关资源
    最近更新 更多