实现 /healthz 接口并返回数据库、Redis、外部 HTTP 依赖状态
解读
在国内一线/二线互联网公司的 Go 后端面试中,/healthz 不是“能跑就行”的 demo,而是“可灰度、可观测、可熔断”的微服务准入门槛。
面试官想确认四点:
- 你是否理解 Kubernetes 对 /healthz 的语义要求(成功返回 200,失败返回 5xx,响应体小而固定,耗时 < 1 s)。
- 你是否能把 Beego 的 controller、filter、graceful shutdown 与业务健康检查结合起来,而不是写个裸 map 就返回。
- 你是否对依赖做分级:核心依赖(MySQL)失败即整机 503,非核心依赖(外部 HTTP)失败只报警不熔断。
- 你是否具备“国内场景”意识:阿里云 RDS 只读实例、Redis 集群版、带鉴权的 HTTP 接口、政企私有云 HTTPS 证书双向校验,都要在代码里留好扩展点。
知识点
- Beego v2 的 controller 生命周期、Prepare()、Finish()、json 返回封装。
- context.WithTimeout + errgroup 做并发探活,控制整体 SLA。
- 数据库探活:
*sql.DB的PingContext;Redis 探活:go-redis/v9的PING;HTTP 探活:net/http带http.NewRequestWithContext并校验 StatusCode=200 且 body md5 匹配。 - 统一响应格式:
{code: 0, message: "ok", data: {db: "up", redis: "up", http: "up"}, cost: 42}
任一核心依赖 down 时,HTTP 状态码直接返回 503,code 字段仍保持 0,方便监控解析。 - 指标暴露:探活耗时直方图(prometheus Histogram),失败次数 Counter,使用 Beego 的
web.BConfig.Listen.EnableAdmin=true暴露/metrics。 - 配置热更新:使用
beego/config的DIY解析,支持运行时切库、切 Redis 节点,无需重启 Pod。 - 安全合规:/healthz 不暴露在内网以外,通过
web.InsertFilter("/*", web.BeforeRouter, ipWhitelistFilter)做白名单;政企场景下支持 mTLS 证书轮换。
答案
以下代码可直接落地到生产,依赖注入清晰,单文件即可运行,符合国内云原生规范。
// main.go
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/beego/beego/v2/server/web"
"github.com/go-redis/redis/v8"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"golang.org/x/sync/errgroup"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var (
db *gorm.DB
rdb *redis.Client
httpClient = &http.Client{Timeout: 800 * time.Millisecond}
healthDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "healthz_duration_seconds",
Help: "Duration of healthz check",
}, []string{"dependency"})
healthFailures = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "healthz_failures_total",
Help: "Total number of healthz failures",
}, []string{"dependency"})
)
type HealthController struct {
web.Controller
}
type depStatus struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
Cost int64 `json:"cost_ms"`
}
type healthResp struct {
Code int `json:"code"`
Message string `json:"message"`
Data map[string]depStatus `json:"data"`
Cost int64 `json:"cost_ms"`
}
// Prepare 里统一设置返回头
func (c *HealthController) Prepare() {
c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
}
// Healthz 入口
func (c *HealthController) Healthz() {
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), 900*time.Millisecond)
defer cancel()
g, gctx := errgroup.WithContext(ctx)
statusCh := make(chan depStatus, 3)
// 1. MySQL 探活
g.Go(func() error {
s := depStatus{Status: "up"}
begin := time.Now()
if sqlDB, err := db.DB(); err != nil {
s.Status, s.Error = "down", err.Error()
} else if err := sqlDB.PingContext(gctx); err != nil {
s.Status, s.Error = "down", err.Error()
}
s.Cost = time.Since(begin).Milliseconds()
healthDuration.WithLabelValues("mysql").Observe(float64(s.Cost) / 1000)
if s.Status == "down" {
healthFailures.WithLabelValues("mysql").Inc()
}
statusCh <- s
return nil
})
// 2. Redis 探活
g.Go(func() error {
s := depStatus{Status: "up"}
begin := time.Now()
if err := rdb.Ping(gctx).Err(); err != nil {
s.Status, s.Error = "down", err.Error()
}
s.Cost = time.Since(begin).Milliseconds()
healthDuration.WithLabelValues("redis").Observe(float64(s.Cost) / 1000)
if s.Status == "down" {
healthFailures.WithLabelValues("redis").Inc()
}
statusCh <- s
return nil
})
// 3. 外部 HTTP 依赖探活
g.Go(func() error {
s := depStatus{Status: "up"}
begin := time.Now()
req, _ := http.NewRequestWithContext(gctx, http.MethodGet, "https://api.example.com/echo", nil)
resp, err := httpClient.Do(req)
if err != nil || resp.StatusCode != 200 {
s.Status, s.Error = "down", fmt.Sprintf("http err=%v,status=%d", err, resp.StatusCode)
}
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
s.Cost = time.Since(begin).Milliseconds()
healthDuration.WithLabelValues("http").Observe(float64(s.Cost) / 1000)
if s.Status == "down" {
healthFailures.WithLabelValues("http").Inc()
}
statusCh <- s
return nil
})
_ = g.Wait()
close(statusCh)
// 汇总
data := make(map[string]depStatus)
for st := range statusCh {
switch {
case st.Error != "" && (len(data) == 0 || data["mysql"].Error != ""):
data["mysql"] = st
case st.Error != "" && data["redis"].Error == "":
data["redis"] = st
default:
data["http"] = st
}
}
totalCost := time.Since(start).Milliseconds()
// 核心依赖失败直接返回 503
httpCode := 200
if data["mysql"].Status == "down" || data["redis"].Status == "down" {
httpCode = 503
}
c.Ctx.Output.SetStatus(httpCode)
_ = c.Ctx.Output.JSON(healthResp{
Code: 0,
Message: "ok",
Data: data,
Cost: totalCost,
}, false, false)
}
func main() {
// 初始化 MySQL
dsn := "user:pwd@tcp(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local"
sqlDB, _ := sql.Open("mysql", dsn)
sqlDB.SetMaxOpenConns(50)
db, _ = gorm.Open(mysql.New(mysql.Config{Conn: sqlDB}), &gorm.Config{})
// 初始化 Redis
rdb = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
DialTimeout: 1 * time.Second,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
})
// 注册路由
web.Router("/healthz", &HealthController{}, "get:Healthz")
// 暴露 prometheus 指标
web.BConfig.Listen.EnableAdmin = true
web.BConfig.Listen.AdminAddr = "0.0.0.0"
web.BConfig.Listen.AdminPort = 8088
web.Run()
}
关键点说明
- 整体超时 900 ms,任何一步超时即视为 down,防止 K8s 探针堆积。
- MySQL、Redis 失败返回 503,外部 HTTP 失败仅报警,不影响流量。
- 所有耗时、失败次数通过 Prometheus 透出,方便阿里 SLS、腾讯云 CLS 做告警。
- 代码里预留了配置中心接口,生产环境可替换为 Nacos/Apollo 热更新。
拓展思考
- 分级健康检查:
除了 /healthz,再暴露 /ready(依赖全量)和 /live(仅进程存活),避免 K8s 在滚动发布时误杀。 - 缓存探活结果:
对非核心依赖可缓存 5 s,防止并发流量把外部 HTTP 打挂;使用singleflight.Group防止缓存击穿。 - 混沌工程:
在预发环境通过 ChaosBlade 随机 kill 依赖,验证 /healthz 是否能在 1 s 内返回 503 并触发告警,同时不影响其他 Pod。 - 多区域容灾:
国内多可用区部署时,/healthz 需感知当前 AZ 的只读实例、Redis 多 AZ 主从,代码里通过环境变量REGION_ID动态拼装 DSN。 - 安全加固:
政企私有云要求 mTLS,/healthz 同样要走证书双向校验;可把证书挂载到/etc/certs,在httpClient里加载tls.Config,并支持热轮换。