golang服务健康检查简化插件库go-health的使用
golang服务健康检查简化插件库go-health的使用
简介
go-health是一个简化服务健康检查的Golang库,它提供了以下功能:
- 服务健康状态检查
- 优雅停机模式(Graceful Shutdown)
- 外部依赖项健康检查
- 开箱即用的HTTP处理器,返回健康状态
安装
go get -u github.com/Talento90/go-health
使用示例
下面是一个完整的使用示例:
package main
import (
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/Talento90/go-health"
)
func main() {
// 创建Health实例
h := health.New("my-service", health.Options{CheckersTimeout: time.Second * 1})
// 注册外部依赖检查器(示例中使用了模拟对象)
h.RegisterChecker("redis", &mockDB{name: "redis"})
h.RegisterChecker("mongo", &mockDB{name: "mongo"})
h.RegisterChecker("external_api", &mockAPI{})
// 获取服务健康状态
s := h.GetStatus()
_ = s // 使用状态信息
// 监听中断信号以实现优雅停机
var gracefulShutdown = make(chan os.Signal)
signal.Notify(gracefulShutdown, syscall.SIGTERM)
signal.Notify(gracefulShutdown, syscall.SIGINT)
go func() {
<-gracefulShutdown
h.Shutdown()
// 在这里可以优雅地关闭数据库连接
// 优雅地关闭HTTP服务器
}()
// 注册HTTP健康检查端点
http.HandleFunc("/health", h.ServeHTTP)
http.ListenAndServe(":8080", nil)
}
// 模拟数据库检查器
type mockDB struct {
name string
}
func (m *mockDB) Check() error {
// 这里实现实际的健康检查逻辑
// 返回nil表示健康,返回error表示不健康
return nil
}
// 模拟API检查器
type mockAPI struct{}
func (m *mockAPI) Check() error {
// 这里实现实际的API健康检查逻辑
return nil
}
响应示例
健康检查端点会返回如下格式的JSON响应:
{
"service":"imgart",
"up_time":"14m5.788341028s",
"start_time":"2018-03-11T17:02:33Z",
"memory":{
"current":{
"total_alloc":8359984,
"heap_alloc":2285896,
"rss":5767168
},
"initial":{
"total_alloc":7784792,
"heap_alloc":1754064,
"rss":5701632
},
"diff":{
"total_alloc":575192,
"heap_alloc":531832,
"rss":65536
}
},
"go_routines":21,
"is_shutting_down":false,
"health_checkers":{
"mongo":{
"status":"CHECKED",
"response_time":"573.813µs"
},
"redis":{
"status":"CHECKED",
"error":{
"Syscall":"getsockopt",
"Err":113
},
"response_time":"93.526014ms"
},
"external_api": {
"status":"TIMEOUT",
"response_time":"1.2s"
}
}
}
关键特性说明
- 健康检查器(Checker): 任何实现了
Check() error
方法的对象都可以作为健康检查器注册 - 优雅停机: 当接收到SIGTERM或SIGINT信号时,
Shutdown()
方法会将服务标记为正在关闭 - HTTP处理器:
ServeHTTP
方法会自动返回503状态码(Service Unavailable)如果服务正在关闭 - 超时控制: 可以通过Options设置检查器的超时时间
这个库简化了服务健康检查的实现,特别适合微服务架构中的服务健康监控需求。
更多关于golang服务健康检查简化插件库go-health的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang服务健康检查简化插件库go-health的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
go-health库使用指南
go-health是一个用于Golang服务的健康检查简化插件库,它提供了一种简单的方式来监控服务的健康状况并暴露检查结果。
安装
go get github.com/InVisionApp/go-health
基本使用
1. 初始化健康检查器
import (
"github.com/InVisionApp/go-health"
"github.com/InVisionApp/go-health/handlers"
"net/http"
)
func main() {
// 创建健康检查器实例
h := health.New()
// 配置健康检查器
err := h.Start()
if err != nil {
panic("Failed to start health checker")
}
// 注册HTTP处理程序
http.HandleFunc("/healthcheck", handlers.NewJSONHandlerFunc(h, nil))
http.ListenAndServe(":8080", nil)
}
2. 添加自定义检查项
type myCustomCheck struct{}
// 实现Checker接口
func (c *myCustomCheck) Status() (interface{}, error) {
// 在这里实现你的健康检查逻辑
// 返回nil表示健康,返回error表示不健康
return nil, nil
}
func addCustomCheck(h health.IHealth) {
// 创建检查配置
check := &health.Config{
Name: "database-check",
Checker: &myCustomCheck{},
Interval: time.Duration(5) * time.Second,
Fatal: true, // 如果此项检查失败,整个服务视为不健康
}
// 添加检查项
if err := h.AddCheck(check); err != nil {
panic("Failed to add health check")
}
}
3. 完整示例
package main
import (
"fmt"
"github.com/InVisionApp/go-health"
"github.com/InVisionApp/go-health/handlers"
"net/http"
"time"
)
// 数据库健康检查
type DBCheck struct{}
func (c *DBCheck) Status() (interface{}, error) {
// 这里模拟数据库检查
// 实际应用中应该执行真正的数据库查询
if time.Now().Unix()%2 == 0 {
return nil, fmt.Errorf("database connection failed")
}
return map[string]interface{}{"connections": 10}, nil
}
// 外部API健康检查
type APICheck struct{}
func (c *APICheck) Status() (interface{}, error) {
// 模拟外部API检查
if time.Now().Unix()%3 == 0 {
return nil, fmt.Errorf("API timeout")
}
return "ok", nil
}
func main() {
// 初始化健康检查器
h := health.New()
// 添加数据库检查
dbCheck := &health.Config{
Name: "database",
Checker: &DBCheck{},
Interval: time.Duration(2) * time.Second,
Fatal: true,
}
// 添加API检查
apiCheck := &health.Config{
Name: "external-api",
Checker: &APICheck{},
Interval: time.Duration(3) * time.Second,
Fatal: false,
}
if err := h.AddChecks([]*health.Config{dbCheck, apiCheck}); err != nil {
panic(err)
}
// 启动健康检查器
if err := h.Start(); err != nil {
panic(err)
}
// 设置HTTP路由
http.HandleFunc("/health", handlers.NewJSONHandlerFunc(h, nil))
http.HandleFunc("/health/basic", handlers.NewBasicHandlerFunc(h))
fmt.Println("Server started at :8080")
http.ListenAndServe(":8080", nil)
}
高级功能
1. 自定义响应格式
http.HandleFunc("/health/custom", func(w http.ResponseWriter, r *http.Request) {
state, details, err := h.State()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintf(w, "Service Unhealthy: %v", err)
return
}
if !state {
w.WriteHeader(http.StatusServiceUnavailable)
}
// 自定义响应格式
fmt.Fprintf(w, "Status: %v\nDetails: %+v", state, details)
})
2. 监听健康状态变化
h.AddListener(&health.StateListener{
Name: "my-listener",
OnStateChange: func(name string, state health.State) {
fmt.Printf("Check '%s' changed state to %v\n", name, state)
},
})
3. 动态添加/移除检查
// 动态添加检查
newCheck := &health.Config{
Name: "new-check",
Checker: &APICheck{},
Interval: time.Duration(10) * time.Second,
}
h.AddCheck(newCheck)
// 动态移除检查
h.RemoveCheck("database")
最佳实践
- 关键组件检查:为数据库、缓存、外部API等关键依赖项添加健康检查
- 合理设置检查间隔:根据组件特性设置适当的检查频率
- 区分致命与非致命检查:使用
Fatal
标记区分服务核心组件和非核心组件 - 提供详细信息:在检查器的
Status()
方法中返回有用的诊断信息 - 监控健康状态:使用监听器记录健康状态变化,便于问题排查
go-health库简化了服务健康检查的实现,通过简单的API即可构建全面的健康监控系统,非常适合微服务架构中的服务健康管理。