golang 框架中的限流和融断开源库主要有 ratelimit、ratelimiter、hystrix-go 和 sentinel-golang。ratelimit:简易令牌桶限流。ratelimiter:丰富的限流对策,如滑动窗口。hystrix-go:断路器,相近 netflix hystrix。sentinel-golang:集限流、融断和热气操纵于一体。pkg/errors:自定限流和融断错误回应。
GoLang 框架中限流和融断的开源库比较和采用在高并发系统中,为了保障体系的易用性,防止服务雪崩效应,必须引进限流和熔断机制。本文将介绍多种 GoLang 架构常用的限流和融断开源库,并通过实战案例 数据分析他们的特征,协助开发者根据自身需求选用合适的库。
开源库较为库名字方案特性 ratelimit令牌桶简单实用,适用根据局部变量或分布式集群的令牌桶完成 ratelimiter令牌桶、滑动窗口提供大量限流对策,适用灵活配置hystrix-go 断路器与 Netflix Hystrix 相近,给予断路器和监控功能 sentinel-golang限流、融断、热气操纵集限流、融断、热气操纵于一体,功能全面 pkg/errors 自定错误 Go 标准库提供的错误处理包,适合于自定限流和融断错误回应实战案例 令牌桶限流应用 ratelimit库完成令牌桶限流:
import (
"context"
limiter "github.com/juju/ratelimit"
)
func rateLimit(ctx context.Context) {
r := limiter.NewRateLimiter(5, 5)
_ = r.Take(ctx)
}
滑动窗口限流应用 ratelimiter库完成滑动窗口限流:
import(
"context"
ratelimiter"github.com/juju/ratelimit/core"
)
funcslidingWindowRateLimit(ctxcontext.Context){
r:= ratelimiter.NewSlidingWindowRateLimiter(20,10)
_=r.Take()
}
断路器应用hystrix-go 库实现熔断器:
import (
"context"
hystrix "github.com/afex/hystrix-go/hystrix"
)
func hystrixTest(ctx context.Context) {
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
Timeout: 100,
MaxConcurrentRequests: 3,
ErrorPercentThreshold: 25,
SleepWindow: 5,
})
_ = hystrix.ExecuteCommand("my_command", func(ctx context.Context, req string) (string, error) {
return "", nil
})
}
综合限流、融断和热气操纵应用 sentinel-golang库完成综合限流、融断和热气操纵:
import (
sentinel "github.com/alibaba/sentinel-golang/api"
"github.com/alibaba/sentinel-golang/core/flow"
)
func sentinelTest() {
r := flow.NewFlowRule(10, 10)
sentinel.LoadRules([]flow.Rule{r})
_ = sentinel.CheckAndRun("test", func() (interface{}, error) {
return nil, nil
})
}
库采用提议简易限流: ratelimit高端限流: ratelimiter断路器:hystrix-go 综合作用: sentinel-golang自定错误回应: pkg/errors开发者可根据实际需求和项目规模选用合适的库。
以上就是golang框架中限流和融断的开源库比较和采用?的详细内容,大量请关注其他类似文章!