熔断、限流和降级:Sentinel
原创大约 1 分钟
集成&开发
环境和脚本
go get -u github.com/alibaba/sentinel-golang
1. 新增Sentinel中间件
package middleware
import (
sentinel "github.com/alibaba/sentinel-golang/api"
"github.com/alibaba/sentinel-golang/core/flow"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// Sentinel 中间件
func Sentinel() gin.HandlerFunc {
return func(ctx *gin.Context) {
err := sentinel.InitDefault()
if err != nil {
zap.S().Infof("Sentinel初始化失败:%v", err.Error())
}
_, err = flow.LoadRules([]*flow.Rule{
{
Resource: ctx.Request.Method + ":" + ctx.FullPath(),
TokenCalculateStrategy: flow.Direct,
ControlBehavior: flow.Reject,
Threshold: 1,
StatIntervalInMs: 2000,
},
})
if err != nil {
zap.S().Infof("Sentinel规则加载失败:%v", err.Error())
}
ctx.Next()
}
}
2. 修改路由初始化代码
import (
sentinelPlugin "github.com/sentinel-group/sentinel-go-adapters/gin"
......
)
// 处理跨域请求
roots.Use(middleware.Cors())
roots.
// 调用Sentinel中间件
Use(middleware.Sentinel()).
// 在gin中集成Sentinel插件,Resource采用sentinelPlugin的方式
// Resource = ctx.Request.Method + ":" + ctx.FullPath()
Use(sentinelPlugin.SentinelMiddleware(
sentinelPlugin.WithBlockFallback(func(ctx *gin.Context) {
ctx.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
"code": http.StatusTooManyRequests,
"msg": "请求过于频繁,请稍后重试",
"data": gin.H{},
})
})),
)
......
可以看到,通过插件整合的方式,就不需要再在每个接口中都调用下面这样的代码。
e, b := sentinel.Entry("some-test", sentinel.WithTrafficType(base.Inbound))
if b != nil {
// Blocked. We could get the block reason from the BlockError.
time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)
} else {
// Passed, wrap the logic here.
time.Sleep(time.Duration(rand.Uint64()%10) * time.Millisecond)
// Be sure the entry is exited finally.
e.Exit()
}
代码的侵入性几乎为零。
3. 与GRPC的整合(略)
文档写的比较清楚,按照文档来很容易实现。
感谢支持
更多内容,请移步《超级个体》。