1

我有 10 个请求

  val reqTemplate = quickRequest.post(uri"http://localhost:8280/delay/1")
  val requests = for {i <- 1 to 10} yield {
    reqTemplate.body(s"{test:$i}")
  }

如何同时发送这些请求?

我试过


  val responseTasks = reqs.map(SttpClient.send)
  val allResponsesTask: Task[List[Response[String]]] = ZIO.collectAllPar(responseTasks)

  val appLogic: Task[Unit] = for {
    resps <- allResponsesTask
    resp <- resps
    _ <- putStrLn(resp.toString())
    _ <- putStrLn("Done")
  } yield ()

  Runtime.default.unsafeRunAsync(appLogic)

但这给了我各种有趣的编译错误。

Error:(18, 74) type mismatch;
 found   : scala.collection.immutable.IndexedSeq[zio.ZIO[sttp.client.asynchttpclient.zio.SttpClient,Throwable,sttp.client.Response[String]]]
    (which expands to)  scala.collection.immutable.IndexedSeq[zio.ZIO[zio.Has[sttp.client.SttpBackend[zio.Task,Nothing,sttp.client.asynchttpclient.WebSocketHandler]],Throwable,sttp.client.Response[String]]]
 required: Iterable[zio.ZIO[Any,Throwable,sttp.client.Response[String]]]
  val allResponsesTask: Task[List[Response[String]]] = ZIO.collectAllPar(responseTasks)
Error:(23, 7) type mismatch;
 found   : zio.ZIO[zio.console.Console,Nothing,Unit]
    (which expands to)  zio.ZIO[zio.Has[zio.console.Console.Service],Nothing,Unit]
 required: scala.collection.GenTraversableOnce[?]
    _ <- putStrLn(response.toString())
Error:(22, 14) type mismatch;
 found   : List[Nothing]
 required: zio.ZIO[Any,Throwable,Unit]
    response <- responses
4

1 回答 1

0

问题是您已经声明了Sttp依赖项但您没有提供它。

如果你注释responsesTask你会看到它实际上是类型Seq[ZIO[SttpClient, Throwable, Response[String]]],意味着你需要提供一个客户端来满足依赖。

我会将其更改为:

  val allResponsesTask: Task[List[Response[String]]] = 
    ZIO.collectAllPar(responseTasks)
      .provideLayer(AsyncHttpClientZioBackend.layer())

请注意,为了简单起见,我在此处添加了层,但通常您希望在应用程序的边缘添加所有层,因为创建层不是免费的。

于 2020-04-05T05:23:38.903 回答