You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scala SBT项目中集成Prometheus监控指标?

嘿,我来一步步帮你搞定Scala SBT项目集成Prometheus监控的事儿,其实流程挺清晰的,咱们分步骤来:

1. 先在SBT里添加必要依赖

首先得把Prometheus的Java客户端和HTTP暴露工具加进项目。在你的build.sbt里添加这些依赖(版本可以选最新稳定版,这里给个常用版本示例):

libraryDependencies ++= Seq(
  "io.prometheus" % "simpleclient" % "0.16.0",
  "io.prometheus" % "simpleclient_hotspot" % "0.16.0", // 可选,自动收集JVM相关指标(内存、GC等)
  "io.prometheus" % "simpleclient_httpserver" % "0.16.0" // 用来启动HTTP服务器暴露指标端点
)
2. 定义自定义业务指标

接下来你可以根据自己的业务需求创建自定义指标,比如计数器(记录请求数、错误数)、仪表盘(记录当前活跃连接、队列长度)等。建议把指标封装成一个单例对象,方便全局调用:

import io.prometheus.client.{Counter, Gauge}

object AppMetrics {
  // 计数器:记录应用处理的总请求数
  val totalRequests: Counter = Counter.build()
    .name("app_total_requests")
    .help("Total number of requests processed by the application")
    .register()

  // 仪表盘:记录当前活跃的连接数
  val activeConnections: Gauge = Gauge.build()
    .name("app_active_connections")
    .help("Current number of active connections to the application")
    .register()

  // 可选:记录错误请求数的计数器
  val errorRequests: Counter = Counter.build()
    .name("app_error_requests_total")
    .help("Total number of failed requests")
    .labelNames("error_type") // 可以加标签区分不同错误类型
    .register()
}

在业务代码里直接调用这些指标的方法就行,比如处理请求时:

// 每次处理请求就自增计数器
AppMetrics.totalRequests.inc()

// 连接建立时增加仪表盘数值
AppMetrics.activeConnections.inc()
// 连接断开时减少
AppMetrics.activeConnections.dec()

// 发生错误时,给对应标签的计数器自增
AppMetrics.errorRequests.labels("validation_failed").inc()
3. 启动指标暴露的HTTP服务器

Prometheus是通过拉取模式获取指标的,所以咱们需要启动一个HTTP服务器,让Prometheus能访问到指标接口。可以在应用启动时初始化这个服务器:

import io.prometheus.client.exporter.HTTPServer

object Main extends App {
  // 启动HTTP服务器,监听9090端口(你可以自定义这个端口)
  val metricsServer = new HTTPServer(9090)
  println("Metrics server started on port 9090")

  // 模拟你的业务逻辑(这里只是示例,替换成你实际的应用代码)
  while (true) {
    AppMetrics.totalRequests.inc()
    AppMetrics.activeConnections.set(Math.random() * 20) // 模拟活跃连接数变化
    Thread.sleep(1000)
  }

  // 优雅停机时记得关闭服务器(比如在应用关闭钩子中调用)
  // Runtime.getRuntime.addShutdownHook(new Thread(() => metricsServer.stop()))
}
4. 配置Prometheus拉取指标

现在需要修改Prometheus的配置文件(通常是prometheus.yml),把你的Scala应用添加为监控目标:

scrape_configs:
  - job_name: "scala_application"
    scrape_interval: 15s # 每15秒拉取一次指标,可按需调整
    static_configs:
      - targets: ["localhost:9090"] # 这里填你刚才HTTPServer监听的地址和端口

配置完后重启Prometheus服务,它就会自动开始拉取你的应用指标了。

5. 验证指标是否正常工作

启动Scala应用后,直接访问http://localhost:9090/metrics,你应该能看到类似这样的输出,包含你定义的自定义指标和JVM指标(如果加了hotspot依赖):

# HELP app_total_requests Total number of requests processed by the application
# TYPE app_total_requests counter
app_total_requests 42.0
# HELP app_active_connections Current number of active connections to the application
# TYPE app_active_connections gauge
app_active_connections 8.345

如果能看到这些内容,就说明指标暴露成功了,接下来你就可以在Prometheus UI或者Grafana里可视化这些指标啦。

一些实用小建议
  • 指标命名规范:尽量用小写字母加下划线,比如app_total_requests,避免特殊字符和驼峰,符合Prometheus的命名习惯。
  • 添加清晰的Help描述:每个指标的help字段要准确说明指标含义,方便后续排查问题。
  • Web应用集成:如果你的项目是基于Play、Akka HTTP这类Web框架的,可以不用单独启动HTTPServer,直接把/metrics端点集成到现有路由里,返回Prometheus的文本格式即可。
  • 标签的使用:给指标添加标签(比如error_type、endpoint)可以更细粒度地分析数据,比如区分不同接口的请求数。

内容的提问来源于stack exchange,提问作者Shamanth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:52:51