返回顶部

7.【go-kit教程】go-kit限流和熔断

限流

  • go-kit 限流器使用的是令牌桶算法(Token Bucket Algorithm),具体可参考https://bigox.top/pages/27e422/

  • go-kit提供了一个ratelimit包,可以用来限制请求的速率,实现限流功能。以下是一个简单的例子

    import (
        "github.com/go-kit/kit/endpoint"
        "github.com/go-kit/kit/ratelimit"
        "github.com/go-kit/kit/log"
        "golang.org/x/time/rate"
    )
    
    func main() {
        // 创建一个endpoint
        myEndpoint := func(ctx context.Context, request interface{}) (interface{}, error) {
            // 实现你的业务逻辑
        }
    
        // 创建一个速率限制器,每秒允许10个请求
        limiter := rate.NewLimiter(10, 1)
    
        // 使用速率限制器包装endpoint
        limitedEndpoint := ratelimit.NewErroringLimiter(limiter)(myEndpoint)
    
        // 使用日志记录器包装endpoint
        logger := log.NewJSONLogger(os.Stdout)
        limitedEndpoint = LoggingMiddleware(logger)(limitedEndpoint)
    
        // 运行限流的endpoint
        // ...
    }
    
    
  • 或者

    // NewTokenBucketLimitterWithBuildIn 使用x/time/rate创建限流中间件
    func NewTokenBucketLimitterWithBuildIn(bkt *rate.Limiter) endpoint.Middleware {
    	return func(next endpoint.Endpoint) endpoint.Endpoint {
    		return func(ctx context.Context, request interface{}) (response interface{}, err error) {
    			if !bkt.Allow() {
    				return nil, ErrLimitExceed
    			}
    			return next(ctx, request)
    		}
    	}
    }
    
    
    // main.go
    ratebucket := rate.NewLimiter(rate.Every(time.Second*1), 3)
    endpoint = NewTokenBucketLimitterWithBuildIn(ratebucket)(endpoint)
    

熔断

  • 服务熔断是指调用方发现服务提供方响应缓慢或者不可用时,调用方为了自保直接失败,不再调用目标服务。

  • 在Go kit中,可以使用Hystrix来实现服务熔断功能。Hystrix是Netflix开源的一个库,它提供了熔断、线程隔离、超时控制和服务监控等功能,可以很好地应对微服务架构中的服务故障问题。

  • 示例

    import (
        "github.com/afex/hystrix-go/hystrix"
        "github.com/go-kit/kit/circuitbreaker"
        "github.com/go-kit/kit/endpoint"
    )
    
    func main() {
        // 创建一个endpoint
        myEndpoint := func(ctx context.Context, request interface{}) (interface{}, error) {
            // 实现你的业务逻辑
        }
    
        // 使用Hystrix包装endpoint
        hystrix.ConfigureCommand("my-command", hystrix.CommandConfig{
            Timeout:               1000,   // 超时时间
            MaxConcurrentRequests: 10,     // 最大并发请求数
            ErrorPercentThreshold: 50,     // 错误百分比阈值
        })
        breaker := circuitbreaker.Hystrix("my-command")
        hystrixEndpoint := breaker(myEndpoint)
    
        // 运行Hystrix的endpoint
        // ...
    }
    
    
  • 使用了 hystrix.ConfigureCommand() 函数来配置Hystrix的命令。然后,我们使用 circuitbreaker.Hystrix() 函数将endpoint包装起来,生成一个新的endpoint hystrixEndpoint,该endpoint会在服务出现错误时触发熔断,阻止请求继续传递。

posted @ 2023-02-25 22:03  高薪程序员  阅读(53)  评论(0编辑  收藏  举报