如何调试akka http的路由dsl

时间:2017-05-24 11:26:59

标签: scala akka unmarshalling akka-http

我正在尝试为akka http创建一个unmarshaller,从avro转到自定义case类。但它给了我一个非常模糊的错误:“找不到隐含的价值”。我该怎么调试这个或让scala给我提示问题在哪里?

我这样设置路线:

class MetricsRoute(implicit val system: ActorSystem, implicit val materializer: ActorMaterializer) {
import system.dispatcher

  def getRoute() = {
    path("metrics") {
      put {
        decodeRequest {
          entity(as[Metrics]) { metrics: Metrics =>
            println(metrics.time)
            complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>hi!</h1>"))
          }
        }
      }
    }
  }

在同一个班级中,我也创建了这样的unmarshaller:

  implicit def avroUnmarshaller(): FromRequestUnmarshaller[Metrics] =
    Unmarshaller.withMaterializer {
      implicit ex: ExecutionContext =>
      implicit mat: Materializer =>
        request: HttpRequest => {
          val inputStream = request.entity.dataBytes.runWith(
            StreamConverters.asInputStream(FiniteDuration(3, TimeUnit.SECONDS))
          )

          val reader = new SpecificDatumReader[AvroMetrics](classOf[AvroMetrics])
          val decoder:BinaryDecoder = DecoderFactory.get().binaryDecoder(inputStream, null)

          //AvroMetrics is a case class generated from the avro schema
          val avroMetrics:AvroMetrics = AvroMetrics(0, 0, List())
          reader.read(avroMetrics, decoder)

          Future {
            //converts the avro case class to the case class specific for my application
            convertMetrics(avroMetrics)
          }
        }
  }

但是这给了我一个非常模糊的“无法找到隐含价值”的错误:

[error] /mypath/MetricsRoute.scala:34: could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[my.package.types.Metrics]
[error]           entity(as[Metrics]) { metrics: Metrics =>
[error]                    ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

如何调试丢失的内容或我做错了什么?

修改

值得注意的是,当我自己指定unmarshaller它确实有效,所以改变

entity(as[Metrics]) { metrics: Metrics =>

entity(avroUnmarshaller) { metrics: Metrics =>

这似乎表明marshaller代码本身并没有错,但是我对这些类型做错了吗?

1 个答案:

答案 0 :(得分:1)

编译器正在寻找FromRequestUnmarshaller[Metrics],您定义的类型为() => FromRequestUnmarshaller[Metrics]

尝试使用无空括号定义隐式,例如

implicit def avroUnmarshaller: FromRequestUnmarshaller[Metrics] = ???

而不是

implicit def avroUnmarshaller(): FromRequestUnmarshaller[Metrics] = ???

(另外,它可以是val,但这与此问题无关)