gpt4 book ai didi

multithreading - Scala 中的同步和异步客户端代码

转载 作者:行者123 更新时间:2023-12-02 05:32:18 24 4
gpt4 key购买 nike

这是我的旧 question 的后续内容。假设我需要同步和异步调用 REST 服务。在同步情况下,我想在调用者线程上执行此操作,而不从池中获取其他线程。

我只想编写我的业务逻辑一次并在两种情况下重用它。业务逻辑包括构建请求和处理响应。

我还想组合 REST 调用,就像“调用服务 A,然后调用服务 B,然后调用服务 C”

你会如何在 Scala 中做到这一点?

最佳答案

这应该在当前线程中运行...

{
val currentThreadEx = new AbstractExecutorService {
override def execute(r: Runnable) { r.run }
override def shutdownNow(): java.util.List[Runnable] = new java.util.ArrayList[Runnable]()
override def shutdown() {}
override def isTerminated = false
override def isShutdown = false
override def awaitTermination(timeout: Long, unit: TimeUnit) = false
}
implicit val exContext = ExecutionContext.fromExecutor(currentThreadEx)

val f = Future {
10 + 1
}

println(Await.result(f, 1 seconds))
}

这将在默认执行器上运行...

{
import ExecutionContext.Implicits.global

val f = Future {
10 + 1
}

println(Await.result(f, 1 seconds))
}

如您所见,您可以使用 ExecutorService 作为抽象点。

或者您可以使用用 Monad 编写的函数,然后您可以将这些操作绑定(bind)在一起,而无需处理上下文(即 Future)。

  def op1[M[_]: Monad](i: Int)(j: Int): M[Int] = {
Monad[M].point { i * j }
}

println(Monad[Id].point(10) >>= op1[Id](10))
println((Future { 10 } >>= op1[Future](10)).run)

关于multithreading - Scala 中的同步和异步客户端代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com