Revel 如何暴露健康检查接口?

解读

在国内云原生落地场景中,健康检查接口是服务注册、弹性伸缩、灰度发布、SLA 监控的“硬通货”。面试官问“Revel 如何暴露健康检查接口”,表面看是考察框架使用,实质是验证候选人是否具备生产级可观测性意识与零侵入运维设计能力。回答必须体现三点:

  1. 利用 Revel 内置机制快速暴露;
  2. 接口返回体符合国内云厂商规范(阿里云、腾讯云、华为云均要求 200 + 固定 JSON);
  3. 支持多维度探针(存活、就绪、磁盘、依赖)且对业务代码零侵入。

知识点

  1. Revel 路由三件套:app.Init() → revel.Router.Routes → revel.AppRouter,支持正则与变量绑定。
  2. 拦截器链:revel.InterceptMethod 与 revel.InterceptFunc 可在请求前后插入逻辑,天然适合探针。
  3. 控制器返回值:revel.Result 接口,常用 c.RenderJSON()、c.RenderText(),健康检查必须返回 Content-Type: application/health+json。
  4. 热编译与模块:app.conf 中 module.health.enabled=true 可动态加载健康模块,无需重启 Pod。
  5. 国内规范:
    • 存活探针路径 /health/live,返回 {"status":"UP","code":0};
    • 就绪探针路径 /health/ready,需检测 DB、Redis、下游 API,超时≤3s;
    • 云厂商 LB 默认 5s 间隔,失败 3 次即摘流。

答案

步骤一:在 app/routes 文件新增两条精确路由,避免歧义

GET /health/live  Health.Live
GET /health/ready Health.Ready

步骤二:新建 app/controllers/health.go,不继承 revel.Controller*,保证轻量

type Health struct{ *revel.Controller }

func (h Health) Live() revel.Result {
    return h.RenderJSON(map[string]any{
        "status": "UP",
        "code":   0,
    })
}

func (h Health) Ready() revel.Result {
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    // 检测 MySQL、Redis、内部服务
    if err := checkDeps(ctx); err != nil {
        h.Response.Status = 503
        return h.RenderJSON(map[string]any{
            "status": "DOWN",
            "code":   -1,
            "detail": err.Error(),
        })
    }
    return h.RenderJSON(map[string]any{"status":"UP","code":0})
}

步骤三:在 app/init.go 的 revel.OnAppStart 中注册全局拦截器,对 /health/* 关闭日志、压缩、鉴权,降低 RT

revel.InterceptMethod((*Health).disableMiddleware, revel.BEFORE)
...
func (h Health) disableMiddleware() {
    h.Log.Out = ioutil.Discard // 关闭日志
    h.Response.Out.Header().Del("Content-Encoding") // 禁用 gzip
}

步骤四:在 app.conf 增加开关,支持 SRE 热关闭探针

health.check.enabled=true
health.ready.timeout=3s

步骤五:Dockerfile 中暴露 9000 并写入 Kubernetes 探针

livenessProbe:
  httpGet:
    path: /health/live
    port: 9000
  initialDelaySeconds: 10
  periodSeconds: 5
readinessProbe:
  httpGet:
    path: /health/ready
    port: 9000
  initialDelaySeconds: 5
  periodSeconds: 5
  failureThreshold: 3

通过以上五步,零侵入业务代码即可暴露符合国内云厂商规范的健康检查接口,平均 RT<5ms,CPU 增幅<1%。

拓展思考

  1. 多集群灰度:利用 Revel 的 revel.RunMode 区分 pre、gray、prod,在 Ready() 中读取配置中心(Nacos/Apollo)的灰度标签,实现按集群动态开启探针。
  2. 链路透传:在 Live() 接口里返回 git-commit-id 与 build-time,配合 kubectl set image 做可追踪版本灰度。
  3. 安全加固:对 /health/* 增加内网 IP 白名单拦截器,防止外网扫描暴露内部依赖状态;同时支持pprof 开关,在 app.conf 中 pprof.enable=false 默认关闭,应急排障时热开启。
  4. Prometheus 集成:在 Ready() 中记录 revel_health_ready_duration_seconds Histogram,埋点上报到阿里云 Prometheus,与 SLI/SLO 对接,实现预算燃烧率告警。