【问题标题】:How to run Akka Streams graph on a separate dispatcher with timeout?如何在具有超时的单独调度程序上运行 Akka Streams 图?
【发布时间】:2017-01-15 20:51:48
【问题描述】:

这个问题是基于我做的一个宠物项目和这个SO 线程。在 Akka HTTP 路由定义中,我启动了一个长时间运行的进程,当然我希望在不阻塞用户的情况下这样做。我可以使用下面的代码 sn-p 来实现这一点:

blocking-io-dispatcher {
  type = Dispatcher
  executor = "thread-pool-executor"
  thread-pool-executor {
    fixed-pool-size = 16
  }
  throughput = 1
}

complete {
  Try(new URL(url)) match {
    case scala.util.Success(u) => {
      val src = Source.fromIterator(() => parseMovies(u).iterator)

      src
        .via(findMovieByTitleAndYear)
        .via(persistMovies)
        .toMat(Sink.fold(Future(0))((acc, elem) => Applicative[Future].map2(acc, elem)(_ + _)))(Keep.right)
        // run the whole graph on a separate dispatcher
        .withAttributes(ActorAttributes.dispatcher("blocking-io-dispatcher"))
        .run.flatten
        .onComplete {
          _ match {
            case scala.util.Success(n) => logger.info(s"Created $n movies")
            case Failure(t) => logger.error(t, "Failed to process movies")
          }
        }

      Accepted
    }
    case Failure(t) => logger.error(t, "Bad URL"); BadRequest -> "Bad URL"
  }
}

如果我已经解决了,那有什么问题呢?问题是我不确定如何设置超时。图的执行创建了一个Future,它在专用blocking-io-dispatcher 上执行直到完成。如果我添加一个 Await 调用,代码块。有没有办法设置超时?

【问题讨论】:

    标签: scala akka akka-stream akka-http


    【解决方案1】:

    completionTimeout 舞台在这里应该有所帮助。下面的例子:

    src
        .completionTimeout(5.seconds)
        ...
        .run.flatten
        .onComplete {
            case scala.util.Success(n) => logger.info(s"Created $n movies")
            case Failure(t: TimeoutException) => logger.error(t, "Timed out")
            case Failure(t) => logger.error(t, "Failed to process movies")
        }
    

    文档参考here

    【讨论】:

    • 谢谢你;但是您的代码不会如图所示编译。 completionTimeout 必须在尝试实现图形之前应用 (toMat)。我接受了你的回答,几乎是正确的。
    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多