0

您好,我正在编写 scala 代码以从 API 中提取数据。数据是分页的,所以我按顺序提取数据。现在,我正在寻找一种解决方案来并行拉动多个页面并坚持以编程方式而不是 Inject 创建 WSClient。

任何人都有创建 WSClient 的解决方案?

我找到了一个 AhcWSClient(),但它需要隐式导入演员系统。

4

2 回答 2

3

当您无法按照另一个答案中的建议注入一个时,您可以使用以下方法创建一个独立的 WS 客户端

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws._
import play.api.libs.ws.ahc.StandaloneAhcWSClient

implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val ws = StandaloneAhcWSClient()
于 2019-09-12T15:24:29.450 回答
2

无需在这里重新发明轮子。而且我不确定你为什么说你不能注入WSClient. 如果您可以注入 a WSClient,那么您可以执行以下操作来并行运行请求:

class MyClient @Inject() (wsClient: WSClient)(implicit ec: ExecutionContext) {

  def getSomething(urls: Vector[String]): Future[Something] = {
    val futures = urls.par.map { url =>
      wsClient.url(url).get()
    }
    Future.sequence(futures).map { responses =>
      //process responses here. You might want to fold them together
    }
  }

}
于 2018-12-07T14:33:14.823 回答