如何在Golang中实现微服务健康检查_检测服务可用性

健康检查需区分“进程存活”与“服务可用”,/health仅查自身状态,/health/ready同步检查依赖并限时≤3s,返回标准JSON结构,支持可组合Checker、缓存异步结果及K8s探针集成。

在 Go 微服务架构中,健康检查(Health Check)是保障系统可观测性与弹性的重要机制。它不是简单返回一个 200 OK,而是要真实反映服务的**内部状态**:依赖是否就绪、数据库是否连通、缓存是否可用、队列是否积压等。核心在于——区分“进程存活”和“服务可用”

定义标准健康检查接口(HTTP + JSON)

遵循 [RFC 8417](https://datatracker.ietf.org/doc/html/rfc8417) 建议,暴露 /health(基础存活)和 /health/ready(就绪,用于负载均衡器探活)两个端点:

  • /health:只检查自身进程状态(如 goroutine 数量、内存压力),响应快、无副作用
  • /health/ready:同步检查所有关键依赖(DB、Redis、下游服务),超时需明确控制(建议 ≤ 3s)

返回结构推荐使用标准字段:status("up"/"down"/"degraded")、checks(各组件详情)、versiontimestamp

用 http.Handler 实现可组合的健康检查器

避免硬编码逻辑,用函数式设计封装检查项:

type Checker func() (string, error)

func DBChecker(db *sql.DB) Checker {
    return func() (string, error) {
        ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
        defer cancel()
        if err := db.PingContext(ctx); err != nil {
            return "database", fmt.Errorf("ping failed: %w", err)
        }
        return "database", nil
    }
}

func RedisChecker(client *redis.Client) Checker {
    return func() (string, error) {
        ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
        defer cancel()
        if _, err := client.Ping(ctx).Result(); err != nil {
            return "redis", fmt.Errorf("ping failed: %w", err)
        }
        return "redis", nil
    }
}

在 handler 中聚合执行:

func readyHandler(checkers map[string]Checker) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        results := make(map[string]map[string]interface{})
        status := "up"
        
        for name, check := range checkers {
            start := time.Now()
            componentStatus, err := check()
            duration := time.Since(start).Milliseconds()
            
            results[name] = map[string]interface{}{
                "status":  err == nil,
                "latency_ms": duration,
                "error":   err,
            }
            if err != nil {
                status = "down"
            }
        }
        
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]interface{}{
            "status":    status,
            "checks":    results,
            "timestamp": time.Now().UTC().Format(time.RFC3339),
        })
    }
}

集成到 Gin / Echo 等框架并配置探针

以 Gin 为例,注册路由并设置超时中间件防止阻塞:

r := gin.Default()
r.Use(func(c *gin.Context) {
    c.Next()
    if c.Writer.Status() == http.StatusOK && 
       strings.HasPrefix(c.Request.URL.Path, "/health/") {
        c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
    }
})

checkers := map[string]Checker{
    "database": DBChecker(db),
    "redis":    RedisChecker(redisClient),
}
r.GET("/health/ready", readyHandler(checkers))
r.GET("/health", liveHandler()) // liveHandler 只返回 { "status": "up" }

Kubernetes 配置示例(liveness/readiness probe):

livenessProbe:
  httpGet:
    path: /health
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /health/ready
    port: 8080
  initialDelaySeconds: 5
  periodSeconds: 5
  timeoutSeconds: 3

注意:readinessProbe 超时必须短于 periodSeconds,否则会反复失败重启。

进阶:支持异步检查与缓存结果

对耗时依赖(如第三方 API),避免每次请求都调用。可用 sync.Map 缓存最近一次结果(带 TTL):

type CachedChecker struct {
    checker Checker
    cache   sync.Map // key: string (name), value: cachedResult
}

type cachedResult struct {
    status string
    err    error
    at     time.Time
}

func (c *CachedChecker) Check(name string) (string, error) {
    if val, ok := c.cache.Load(name); ok {
        cr := val.(cachedResult)
        if time.Since(cr.at) < 10*time.Second {
            return cr.status, cr.err
        }
    }
    
    status, err := c.checker()
    c.cache.Store(name, cachedResult{status: status, err: err, at: time.Now()})
    return status, err
}

适合低频变更、高成本检查项(如证书有效期、配置中心连接)。但数据库/缓存类强依赖仍建议实时检查,避免掩盖瞬时故障。

健康检查不是摆设,而是服务自治的起点。把 “能连上” 和 “能干活” 分开判断,用结构化输出支撑告警与自动扩缩容,微服务才真正具备生产就绪能力。