如何将 Prometheus Metrics Middleware 与 http4s DSL 服务集成

How to integrate Prometheus Metrics Middleware with http4s DSL service

为了分析我们的 ember 服务器的性能问题,尝试使用此处提到的文档获取 prometheus 上的服务器指标:https://http4s.org/v0.23/middleware/

build.sbt

      "org.http4s"            %% "http4s-ember-server"       % "0.23.1",
      "org.http4s"            %% "http4s-blaze-client"       % "0.23.1",
      "org.http4s"            %% "http4s-dsl"                % "0.23.1",
      "org.http4s"            %% "http4s-prometheus-metrics" % "0.23.1"

示例代码:

import cats.effect._
import org.http4s.metrics.prometheus.Prometheus
import io.prometheus.client.CollectorRegistry
import org.http4s.server.middleware.Metrics

// build router
val testRoute: Resource[IO, HttpRoutes[IO]] = Prometheus
    .metricsOps[IO](registry, "server")
    .map(ops =>
         Metrics[IO](ops)( {
            val dsl = new Http4sDsl[IO] {}
            import dsl._
            HttpRoutes.of[IO] { 
                case req @ POST -> Root / "test" => 
                  OK("test Ok!")
                case _: Exception =>
                  InternalServerError()
             }
           )
        )
     )

// build server with the router
EmberServerBuilder
  .default[IO]
  .withHost(Host.fromString("0.0.0.0").get)
  .withPort(Port.fromInt(8080).get)
  .withHttpApp(testRoute.orNotFound)
  .build

  1. .withHttpApp(testRoute.orNotFound) 出现编译错误,这是预料之中的,但不确定解决方案。这是一个没有 Prometheus 和 Metrics 包装的工作示例。
  2. 这绝对是一个兼容性问题,但不确定如何包装中间件(这不应该将包装时发生的 return 类型从 HttpRoutes[IO] 更改为 Resource[IO, HttpRoutes[IO]]测试路线。

我是函数式编程方式的新手(对 Scala、Cats lib 和 http4s 也是如此),所有这些泛型似乎都太令人困惑了。

尝试:

// build server with the router
testRoute.flatMap { route =>
  EmberServerBuilder
    .default[IO]
    .withHost(Host.fromString("0.0.0.0").get)
    .withPort(Port.fromInt(8080).get)
    .withHttpApp(route.orNotFound)
    .build
}

您需要将来自 prometheus 的 Resource[IO, HttpRoutes[IO]] 与来自 http4s 的 Resource[IO, Server] 组合起来。