Golang实现的健康检查接口通过/healthz和/readyz路径分别支持K8s的Liveness和Readiness探针,确保服务稳定;其中/healthz返回200表示存活,/readyz可检查数据库等依赖,避免流量进入未就绪实例,配合合理探针配置提升可靠性。

在Kubernetes环境中,服务的稳定性依赖于有效的健康检查机制。Golang作为云原生生态的主流语言,非常适合用来实现轻量、高效的健康检查接口,配合K8s的探针(Liveness、Readiness、Startup Probe)确保应用正常运行。
一个典型的健康检查HTTP接口返回简单的状态信息。通常使用/healthz作为探针路径(Liveness),/readyz用于就绪检查(Readiness)。
核心逻辑包括:
示例代码:
立即学习“go语言免费学习笔记(深入)”;
package main
<p>import (
"net/http"
"time"
)</p><p>func main() {
mux := http.NewServeMux()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// Liveness探针
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
// Readiness探针(可扩展依赖检查)
mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
// 模拟检查数据库连接等
if isReady() {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ready"))
} else {
http.Error(w, "not ready", http.StatusServiceUnavailable)
}
})
server := &http.Server{
Addr: ":8080",
Handler: mux,
}
server.ListenAndServe()}
// 模拟服务就绪判断 func isReady() bool { // 实际项目中可加入DB、Redis等检查 return true }
Kubernetes通过探针自动管理Pod生命周期。合理配置能避免流量进入未就绪服务,或及时重启异常实例。
YAML配置示例:
ports:
- containerPort: 8080
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 10
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /readyz
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
startupProbe:
httpGet:
path: /healthz
port: 8080
failureThreshold: 30
periodSeconds: 10
timeoutSeconds: 5
对于复杂服务,Readiness检查可结合上下文判断依赖状态。
例如检查数据库连接:
import "database/sql"
<p>var db *sql.DB</p><p>func isReady() bool {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if err := db.PingContext(ctx); err != nil {
return false
}
return true}
注意不要在/healthz中加入过多外部依赖检查,避免级联故障影响Liveness判断。
基本上就这些。Golang实现健康检查简单高效,配合K8s探针能显著提升服务可靠性。关键是区分好Liveness和Readiness的语义,避免误判导致服务震荡。
以上就是Golang实现服务健康检查 K8s探针开发的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号