Sentinel is an open source flow control component of Alibaba that is oriented to distributed service architecture. It mainly takes traffic as the entry point and helps developers guarantee the stability of micro-services from multiple dimensions such as flow limiting, traffic shaping, fuse downgrading and system adaptive protection. Sentinel has taken over the core scenarios of Alibaba’s double Eleven in the past 10 years to promote traffic, such as second killing, cold start, message peaking and valley filling, cluster flow control, real-time fusing of downstream unavailable services, etc. Sentinel is a sharp tool to ensure the high availability of micro services. Go-micro uses wrapHandler (server middleware) and WRapClient (client middleware) features to limit incoming and outgoing traffic.
The following uses wrapHandler middleware as an example
- Initialize the sentinal
- Build the HandlerWrapper middleware
package sentinel
import (
"context"
sentinel_api "github.com/alibaba/sentinel-golang/api"
"github.com/alibaba/sentinel-golang/core/base"
"github.com/alibaba/sentinel-golang/core/flow"
"github.com/micro/go-micro/server"
"log"
)
/*
time: 2020/6/10-10:38
author: waiwen
*/
/ / sentinal
func InitSentinel(a) {
err := sentinel_api.InitDefault()
iferr ! =nil {
log.Fatalf("Unexpected error: %+v", err)
}
_, err = flow.LoadRules([]*flow.FlowRule{
{
Resource: "list-limit",
MetricType: flow.QPS,
Count: 10,
ControlBehavior: flow.Reject,
},
})
iferr ! =nil {
log.Fatalf("Unexpected error: %+v", err)
return}}// Build the HandlerWrapper middleware
func NewSentinelHandlerWrapper(a) server.HandlerWrapper {
return func(handlerFunc server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
//name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
resourceName := "list-limit"
entry, err := sentinel_api.Entry(
resourceName,
sentinel_api.WithResourceType(base.ResTypeRPC),
sentinel_api.WithTrafficType(base.Inbound),
)
iferr ! =nil {
return errors.BadRequest("gk.micro.srv.circle"."too many requests")}defer entry.Exit()
return handlerFunc(ctx, req, rsp)
}
}
}
Copy the code
- Configure handlerWrapper when initializing micro Service