Thanos不直接集成到Golang微服务代码中,Go服务只需标准暴露/prometheus指标,由Prometheus抓取后经Sidecar上传至对象存储,Sidecar必须与Prometheus共享TSDB路径,且对象存储配置需在Sidecar、Store Gateway和Compactor间保持一致。

Thanos 本身不直接“集成到 Golang 微服务里”,它是一个独立运行的监控基础设施组件,和你的 Go 服务没有代码级耦合。真正要做的,是让 Go 服务继续按标准方式暴露 Prometheus 指标(用 promhttp),再由外部 Prometheus 抓取,最后通过 Thanos Sidecar 将数据持久化到对象存储。混淆这点,容易在代码里硬塞 Thanos 客户端或误配 remote_write 目标。
Go 服务只需标准暴露 /metrics,别动指标逻辑
你的 Go 微服务唯一要做的,就是正确初始化 Prometheus 注册器并挂载 HTTP handler。Thanos 对指标格式零要求——它只消费 Prometheus 格式文本(text/plain; version=0.0.4)。
- 用
prometheus.NewRegistry()或默认注册器,避免全局变量污染 - 确保
http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))路由存在且可访问 - 不要在 Go 代码里调用
thanos相关包;Thanos 没有官方 Go SDK 用于写入 - 若用了 OpenTelemetry,也只需配置 OTLP exporter 到 Prometheus receiver(如
prometheusremotewriteexporter),而非直连 Thanos
Prometheus 的 scrape 配置决定数据能否进 Thanos
Thanos 不抓取任何东西,它依赖 Prometheus 抓取结果。所以关键在 Prometheus 的 scrape_configs 是否覆盖你的 Go 服务:
- 确认目标地址可达:
targets: ["your-go-service:8080"],且网络策略允许 Prometheus Pod 访问 - 检查
metrics_path是否为/metrics(默认值),非标路径需显式指定 - 若 Go 服务启用了 Basic Auth,必须在
basic_auth下配username/password,否则抓取 401 - 添加
relabel_configs给指标打上业务标签(如job: "auth-service"),后续 Thanos Query 聚合才可区分来源
Thanos Sidecar 必须与 Prometheus 共享 storage.tsdb.path
Sidecar 不是从网络拉指标,而是直接读取 Prometheus 本地 TSDB 文件目录。路径错配会导致“数据上传为空”或“找不到 block”错误。
Colly 是一个用于 Go 语言的快速开源爬取和爬虫框架。它适用于从简单的页面提取到异步爬虫处理大量页面集合,支持请求回调和结构化解析。
立即学习“go语言免费学习笔记(深入)”;
- 启动 Prometheus 时必须指定
--storage.tsdb.path=/prometheus(路径需明确) - Sidecar 启动参数中
--tsdb.path必须完全一致,例如:sidecar --tsdb.path=/prometheus --prometheus.url=http://localhost:9090 - 在 Kubernetes 中,两个容器需挂载同一
emptyDir或 PVC 到该路径,且权限一致(UID/GID 匹配) - 常见坑:
storage.tsdb.path默认是data/,但 Helm chart(如 kube-prometheus-stack)常覆盖为/prometheus,务必核对 values.yaml
对象存储配置错误会导致 Compactor 卡住或 Query 查不到历史
Sidecar 上传成功 ≠ 数据可用。Store Gateway 和 Compactor 都依赖同一份对象存储配置,且必须能解析相同 bucket 中的 block。
-
objstore.yml中bucket名称、endpoint、insecure: true(MinIO 用)、access_key必须三处一致:Sidecar、Store Gateway、Compactor - Compactor 启动后会尝试加锁(
compact/lock文件),若对象存储权限不足或网络不通,日志会卡在acquiring compact lock - Store Gateway 日志出现
no blocks found,大概率是 bucket 空或前缀不匹配(比如 Sidecar 传到了thanos/,而 Store Gateway 查prometheus/) - 用
thanos tools ls --objstore.config-file=objstore.yml手动验证对象存储连通性和内容列表
最容易被忽略的是时间窗口对齐:Prometheus 默认每 2 小时生成一个 block,Sidecar 默认 30 分钟 sync 一次,Compactor 默认 1 小时 run 一次。若网络延迟高或对象存储慢,block 可能“刚生成就过期”,导致 Compactor 跳过压缩。此时得调大 --min-time 和 --max-time 参数,而不是盲目重启组件。

















