golang为Web框架提供生产级功能的插件库go-actuator的使用
Golang为Web框架提供生产级功能的插件库go-actuator的使用
简介
GO Actuator为你的应用程序配置一组执行器端点。它非常具有扩展性,可以与Go的原生HTTP Server Mux或任何第三方Web框架一起使用。
安装
要安装Go Actuator包,你需要先安装Go并设置Go工作空间。
- 首先需要安装Go(需要1.18+版本),然后你可以使用以下Go命令安装Go Actuator:
go get github.com/sinhashubham95/go-actuator
- 在你的代码中导入:
import "github.com/sinhashubham95/go-actuator"
使用方法
执行器库暴露了一个原生的处理函数,应用程序有责任使用这个处理函数。这可以直接与Go的原生HTTP Server Mux一起使用,也可以与任何第三方Web框架一起使用。
配置
配置包含以下内容:
- Endpoints - 这是将被启用的端点列表。这不是一个强制参数。如果没有提供,则只启用
info
和ping
端点。可能的端点是 -/env
,/info
,/health
,/metrics
,/ping
,/shutdown
和/threadDump
。 - Env - 这是应用程序运行的环境。例如,
dev
,stg
,prod
等。 - Name - 这是使用此执行器库的应用程序名称。
- Port - 这是应用程序运行的端口。
- Version - 这是当前应用程序版本。
- Health - 这用于提供一组健康检查器,通过其依赖关系来推导应用程序的健康状况,其中一些可能是强制性的,一些是非强制性的,这有助于保持对应用程序的稳健监控。
import actuator "github.com/sinhashubham95/go-actuator"
config := &actuator.Config{
Endpoints: []int{
actuator.Env,
actuator.Info,
actuator.Metrics,
actuator.Ping,
actuator.Shutdown,
actuator.ThreadDump,
},
Env: "dev",
Name: "Naruto Rocks",
Port: 8080,
Version: "0.1.0",
}
与Go原生Server Mux一起使用
import (
actuator "github.com/sinhashubham95/go-actuator"
"net/http"
)
// 创建一个服务器
mux := &http.ServeMux{}
// 获取执行器的处理程序
actuatorHandler := actuator.GetActuatorHandler(&actuator.Config{})
// 在这个基础端点配置处理程序
mux.Handle("/actuator", actuatorHandler)
// 配置其他处理程序
...
与Fast HTTP一起使用
import (
"strings"
"github.com/valyala/fasthttp"
actuator "github.com/sinhashubham95/go-actuator"
)
// 获取执行器的处理程序
actuatorHandler := fasthttp.NewFastHTTPHandlerFunc(actuator.GetActuatorHandler(&actuator.Config{}))
// 创建一个fast http处理程序
handler := func(ctx *fasthttp.RequestCtx) {
if strings.HasPrefix(ctx.Path(), "/actuator") {
// 使用执行器处理程序
actuatorHandler(ctx)
return
}
// 其他请求处理程序调用
}
fasthttp.ListenAndServe(":8080", handler)
与GIN一起使用
import (
"github.com/gin-gonic/gin"
actuator "github.com/sinhashubham95/go-actuator"
"github.com/sinhashubham95/go-actuator/models"
)
// 创建gin引擎
engine := gin.Default()
// 获取执行器的处理程序
actuatorHandler := actuator.GetActuatorHandler(&actuator.Config{})
ginActuatorHandler := func(ctx *gin.Context) {
actuatorHandler(ctx.Writer, ctx.Request)
}
engine.GET("/actuator/*endpoint", ginActuatorHandler)
与Hertz一起使用
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/adaptor"
"github.com/sinhashubham95/go-actuator"
)
var actuatorHandler = actuator.GetActuatorHandler(&actuator.Config{})
func handleActuator(ctx context.Context, c *app.RequestContext) {
request, err := adaptor.GetCompatRequest(&c.Request)
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
response := adaptor.GetCompatResponseWriter(&c.Response)
actuatorHandler(response, request)
}
s := server.Default()
s.Any("/actuator/*any", handleActuator)
端点
Env - /actuator/env
用于获取应用程序运行时的所有环境变量。注意,要使用此功能,你需要将运行时环境作为应用程序标志传递。
go build
./${APPLICATION_NAME}
响应示例:
{
"env_key_1": "env_value_1",
"env_key_2": "env_value_2"
}
Info - /actuator/info
用于获取应用程序的基本信息。要获取应用程序的正确和相关信息,你需要更改应用程序的构建脚本和运行脚本。
构建脚本示例:
buildStamp=$(date -u '+%Y-%m-%d_%I:%M:%S%p')
commitId=$(git rev-list -1 HEAD)
commitTime=$(git show -s --format=%ci "$commitId")
commitAuthor=$(git --no-pager show -s --format='%an <%ae>' "$commitId")
gitUrl=$(git config --get remote.origin.url)
userName=$(whoami)
hostName=$(hostname)
go build -ldflags "<other linking params> -X github.com/sinhashubham95/go-actuator.BuildStamp=$buildStamp -X github.com/sinhashubham95/go-actuator.GitCommitID=$commitId -X github.com/sinhashubham95/go-actuator.GitPrimaryBranch=$2 -X github.com/sinhashubham95/go-actuator.GitURL=$gitUrl -X github.com/sinhashubham95/go-actuator.Username=$userName -X github.com/sinhashubham95/go-actuator.HostName=$hostName -X \"github.com/sinhashubham95/go-actuator.GitCommitTime=$commitTime\" -X \"github.com/sinhashubham95/go-actuator.GitCommitAuthor=$commitAuthor\""
./${APPLICATION_NAME}
响应示例:
{
"application": {
"env": "ENVIRONMENT",
"name": "APPLICATION_NAME",
"version": "APPLICATION_VERSION"
},
"git": {
"username": "",
"hostName": "",
"buildStamp": "",
"commitAuthor": "Shubham Sinha ",
"commitId": "",
"commitTime": "",
"branch": "",
"url": "",
"startupStamp": ""
},
"runtime": {
"arch": "",
"os": "",
"port": 8080,
"runtimeVersion": ""
}
}
Health - /actuator/health
用于提供应用程序的健康状况,通过各个健康检查验证底层依赖关系。
健康检查可以配置以下详细信息,只有在启用了Health
端点时才需要提供:
import "github.com/sinhashubham95/go-actuator"
cfg := &actuator.Config{
Endpoints: []int{actuator.Health},
Health: &actuator.HealthConfig{
Checkers: []actuator.HealthChecker{
{
Key: "test1",
Func: func(ctx context.Context) error {
// 验证与数据库的连接性
// 或验证与redis的连接性
// 或验证下游api服务
// 等等
},
IsMandatory: true,
},
},
},
}
响应示例:
{
"test1": {
"key": "test1",
"isMandatory": false,
"success": false,
"error": "some error"
},
"test2": {
"key": "test1",
"isMandatory": true,
"success": true
}
}
Metrics - /actuator/metrics
用于获取应用程序的运行时内存统计信息。
响应示例:
{
"alloc": 2047816,
"totalAlloc": 2850832,
"sys": 73942024,
"lookups": 0,
"mAllocations": 15623,
"frees": 9223,
"heapAlloc": 2047816,
"heapSys": 66551808,
"heapIdle": 62832640,
"heapInUse": 3719168,
"heapReleased": 62570496,
"heapObjects": 6400,
"stackInUse": 557056,
"stackSys": 557056,
"mSpanInUse": 81056,
"mSpanSys": 81920,
"MCacheInUse": 19200,
"mCacheSys": 32768,
"buckHashSys": 1446250,
"gcSys": 4225056,
"otherSys": 1047166,
"nextGC": 4194304,
"lastGC": 1627102938524536000,
"pauseTotalNs": 35655,
"pauseNs": [
35655
],
"pauseEnd": [
1627102938524536000
],
"numGC": 1,
"numForcedGC": 0,
"gcCPUFraction": 0.000005360999257331059,
"enableGC": true,
"debugGC": false,
"BySize": [
{
"Size": 0,
"MAllocations": 0,
"Frees": 0
}
]
}
Ping - /actuator/ping
这是一个轻量级的ping端点,可以与你的负载均衡器一起使用。用于了解应用程序的运行状态。
Shutdown - /actuator/shutdown
用于关闭应用程序。
Thread dump - /actuator/threadDump
用于获取所有goroutine的跟踪。
示例输出:
goroutine profile: total 1
1 @ 0x103af45 0x10337fb 0x10688f5 0x10c4de5 0x10c58b5 0x10c5897 0x1117e0f 0x1124391 0x11355e8 0x113576f 0x12037a5 0x1203676 0x1217025 0x1217007 0x121db9a 0x121e5b5 0x106e3e1
# 0x10688f4 internal/poll.runtime_pollWait+0x54 /Users/s0s01qp/go/go1.16.6/src/runtime/netpoll.go:222
# 0x10c4de4 internal/poll.(*pollDesc).wait+0x44 /Users/s0s01qp/go/go1.16.6/src/internal/poll/fd_poll_runtime.go:87
# 0x10c58b4 internal/poll.(*pollDesc).waitRead+0x1d4 /Users/s0s01qp/go/go1.16.6/src/internal/poll/fd_poll_runtime.go:92
# 0x10c5896 internal/poll.(*FD).Read+0x1b6 /Users/s0s01qp/go/go1.16.6/src/internal/poll/fd_unix.go:166
# 0x1117e0e net.(*netFD).Read+0x4e /Users/s0s01qp/go/go1.16.6/src/net/fd_posix.go:55
# 0x1124390 net.(*conn).Read+0x90 /Users/s0s01qp/go/go1.16.6/src/net/net.go:183
# 0x11355e7 bufio.(*Reader).fill+0x107 /Users/s0s01qp/go/go1.16.6/src/bufio/bufio.go:101
# 0x113576e bufio.(*Reader).Peek+0x4e /Users/s0s01qp/go/go1.16.6/src/bufio/bufio.go:139
# 0x12037a4 github.com/valyala/fasthttp.(*RequestHeader).tryRead+0x64 /Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/header.go:1520
# 0x1203675 github.com/valyala/fasthttp.(*RequestHeader).readLoop+0x55 /Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/header.go:1506
# 0x1217024 github.com/valyala/fasthttp.(*RequestHeader).Read+0x1ae4 /Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/header.go:1497
# 0x1217006 github.com/valyala/fasthttp.(*Server).serveConn+0x1ac6 /Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/server.go:2112
# 0x121db99 github.com/valyala/fasthttp.(*workerPool).workerFunc+0xb9 /Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/workerpool.go:223
# 0x121e5b4 github.com/valyala/fasthttp.(*workerPool).getCh.func1+0x34 /Users/s0s01qp/go/pkg/mod/github.com/valyala/fasthttp@v1.28.0/workerpool.go:195
更多关于golang为Web框架提供生产级功能的插件库go-actuator的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang为Web框架提供生产级功能的插件库go-actuator的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Go-Actuator: 为Golang Web框架提供生产级监控功能
go-actuator 是一个轻量级的Golang库,为Web应用提供生产级监控端点,灵感来源于Spring Boot Actuator。它可以帮助开发者轻松地为应用添加健康检查、指标收集、环境信息等生产就绪功能。
主要功能
- 健康检查(/health)
- 应用信息(/info)
- 环境变量(/env)
- 指标收集(/metrics)
- 性能指标(/pprof)
- 自定义端点
安装
go get github.com/sinhashubham95/go-actuator
基本使用示例
1. 与标准库net/http集成
package main
import (
"net/http"
"github.com/sinhashubham95/go-actuator"
)
func main() {
// 创建actuator配置
config := actuator.Config{
Endpoints: []int{
actuator.Health,
actuator.Info,
actuator.Metrics,
actuator.Pprof,
},
Env: "dev",
Name: "example-app",
Port: 8080,
Version: "1.0.0",
}
// 创建actuator处理器
actuatorHandler := actuator.GetActuatorHandler(&config)
// 注册路由
http.Handle("/actuator/", actuatorHandler)
// 启动服务器
http.ListenAndServe(":8080", nil)
}
2. 与Gin框架集成
package main
import (
"github.com/gin-gonic/gin"
"github.com/sinhashubham95/go-actuator"
)
func main() {
r := gin.Default()
// 配置actuator
config := actuator.Config{
Endpoints: []int{
actuator.Health,
actuator.Info,
actuator.Metrics,
actuator.Pprof,
},
Env: "production",
Name: "gin-app",
Port: 8080,
Version: "1.0.0",
}
// 添加actuator路由
actuatorHandler := actuator.GetActuatorHandler(&config)
r.Any("/actuator/*action", gin.WrapH(actuatorHandler))
// 业务路由
r.GET("/", func(c *gin.Context) {
c.String(200, "Hello World!")
})
r.Run(":8080")
}
3. 自定义健康检查
package main
import (
"net/http"
"github.com/sinhashubham95/go-actuator"
)
func main() {
config := actuator.Config{
Endpoints: []int{actuator.Health},
}
// 添加自定义健康检查
actuator.AddHealthIndicator("database", func() (bool, map[string]interface{}) {
// 这里实现数据库健康检查逻辑
return true, map[string]interface{}{
"status": "UP",
"details": "Connection successful",
}
})
http.Handle("/actuator/", actuator.GetActuatorHandler(&config))
http.ListenAndServe(":8080", nil)
}
4. 自定义信息端点
package main
import (
"net/http"
"github.com/sinhashubham95/go-actuator"
)
func main() {
config := actuator.Config{
Endpoints: []int{actuator.Info},
}
// 添加自定义信息
actuator.AddInfo("build", map[string]interface{}{
"artifact": "my-app",
"group": "com.example",
"time": "2023-01-01T00:00:00Z",
})
http.Handle("/actuator/", actuator.GetActuatorHandler(&config))
http.ListenAndServe(":8080", nil)
}
端点说明
-
/health - 应用健康状态
- 返回应用及其依赖的健康状态
- 可以添加自定义健康指示器
-
/info - 应用信息
- 显示应用名称、版本等基本信息
- 可以添加自定义信息
-
/env - 环境变量
- 显示应用的环境变量
- 可用于调试环境配置问题
-
/metrics - 应用指标
- 提供基本的应用指标
- 可以集成Prometheus等监控系统
-
/pprof - 性能分析
- 提供Go的pprof性能分析工具端点
- 可用于CPU、内存分析
安全建议
在生产环境中,建议对actuator端点进行安全保护:
- 通过防火墙限制访问
- 添加认证中间件
- 只暴露必要的端点
// 示例:在Gin中添加基本认证
auth := gin.BasicAuth(gin.Accounts{
"admin": "secret",
})
r.Any("/actuator/*action", auth, gin.WrapH(actuatorHandler))
总结
go-actuator为Golang Web应用提供了简单易用的生产监控功能,可以帮助开发者快速构建生产就绪的应用程序。通过其模块化设计,可以灵活选择需要的功能,并轻松集成到各种Web框架中。
对于更复杂的监控需求,可以考虑结合Prometheus、Grafana等专业监控工具使用。