5

I am looking for an example that shows how you write the Response in an undertow HttpHandler asynchronously? The problem is that when HttpServerExchange.endExchange is called the Response is flushed. My sample HttpHandler uses the rx-java library from Scala.

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)
    }
  }
}
4

1 回答 1

6

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

你可能想要这样的东西:

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

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

于 2014-08-09T21:07:47.503 回答