使用Sttp Client3结合ZLayer开发时出现类型不匹配错误求解
错误根因
直接原因
你在拼接ZLayer时重复拼接了两次HttpBin.live:AsyncHttpClientZioBackend.layer() >>> HttpBin.live 的输出已经是HttpBin类型的层,而HttpBin.live本身要求的输入是SttpClient类型,你第二次用>>>拼接HttpBin.live时,左侧输出的HttpBin类型不满足右侧HttpBin.live要求的输入类型,直接触发了类型不匹配报错。
深层问题
- HttpBin服务的依赖声明错误
你给sendRequest方法声明了多余的HttpBin with SttpClient依赖:作为HttpBin服务内部的方法,本身不需要再依赖HttpBin本身,否则会引入循环依赖风险;同时SttpClient是HttpBin服务的构造依赖,不需要放到每个方法的环境参数中。 - HttpBin.live的实现错误
你使用ZLayer.succeed构造服务实例,没有正确消费传入的SttpClient依赖,即使你传入了SttpClient层,服务内部也拿不到对应的实例。
修复方案
第一步:修正HttpBin服务的定义
object HttpBin { trait Service { // 方法无需额外声明依赖,依赖已在服务构造时注入 def sendRequest: ZIO[Any, Throwable, HttpBinResponse] } // 用ZLayer.fromService获取传入的SttpClient构造服务实例 val live: ZLayer[SttpClient, Nothing, HttpBin] = ZLayer.fromService { sttpBackend => new Service { override def sendRequest: ZIO[Any, Throwable, HttpBinResponse] = { val request = basicRequest .get(uri"https://httpbin.org/get") .response(asJson[HttpBinResponse]) // 直接用注入的sttpBackend发送请求,不需要从环境读取 sttpBackend.send(request).map(_.body).absolve.map(res => HttpBinResponse(res.origin, res.headers)) } } } // 访问方法仅依赖HttpBin即可 def sendRequest: ZIO[HttpBin, Throwable, HttpBinResponse] = ZIO.accessM(_.get.sendRequest) }
第二步:修正Layer拼接逻辑
去掉重复的HttpBin.live拼接即可:
program.provideCustomLayer(AsyncHttpClientZioBackend.layer() >>> HttpBin.live).exitCode
补充说明
你注释掉的可运行代码,program的依赖只有Console和SttpClient:Console属于ZIO默认ZEnv的内置服务,不需要额外提供;你传入AsyncHttpClientZioBackend.layer()正好满足了SttpClient的依赖,所以可以正常运行。
内容的提问来源于stack exchange,提问作者tofu511
相关产品推荐
相关产品推荐

