什么是限流和熔断?详解sentinel限流熔断降级-ag真人官方网

什么是限流和熔断?详解sentinel限流熔断降级-ag真人官方网

来源:php中文网 | 2022-11-13 17:08:02 |

本文由golang教程栏目给大家介绍关于sentinel限流熔断降级,内容包括限流和熔断介绍, alibaba开源的sentinel、安装、实战介绍,希望对需要的朋友有所帮助!

sentinel限流熔断降级

什么是限流 \ 熔断 \ 降级


(资料图片)

限流:在我们的后天系统中,如果那一天突然进入大量流量,我们服务原本最高只能处理同时 2k 的请求,突然一

下就来来了 5k 的请求,这对服务器的压力是不是很要命,这很可能直接导致服务器宕机,崩溃,导致原本 2k 的处

理量都不能处理了,这时候我们需要限流,限流的作用就是保持访问量到达服务器最高的情况下,对多余的请求

不做处理,相比之下,比服务器直接挂掉是好很多的。例如在双十一的时候,我们要下单就会看到类似” 请求繁

忙,请稍后重试!”。

熔断: 相信大家对断路器并不陌生,它就相当于一个开关,打开后可以阻止流量通过。比如保险丝,当电流过大

时,就会熔断,从而避免元器件损坏。

服务熔断是指调用方访问服务时通过断路器做代理进行访问,断路器会持续观察服务返回的成功、失败的状态,

当失败超过设置的阈值时断路器打开,请求就不能真正地访问到服务了。

使用场景

服务故障或者升级时,让客户端快速失败

失败处理逻辑容易定义

响应耗时较长,客户端设置的 read timeout 会比较长,防止客户端大量重试请求导致的连接、线程资源不能释放

* 降级 *: 服务降级是从整个系统的负荷情况出发和考虑的,对某些负荷会比较高的情况,为了预防某些功能(业务

场景)出现负荷过载或者响应慢的情况,在其内部暂时舍弃对一些非核心的接口和数据的请求,而直接返回一个

提前准备好的 fallback(退路)错误处理信息。这样,虽然提供的是一个有损的服务,但却保证了整个系统的稳

定性和可用性。

什么是 sentinel

sentinel 是阿里开源的项目,提供了流量控制、熔断降级、系统负载保护等多个维度来保障服务之间的稳定性。

ag真人官方网官网:github.com/alibaba/sentinel/wiki

2012 年,sentinel 诞生于阿里巴巴,其主要目标是流量控制。2013-2017 年,sentinel 迅速发展,并成为阿里巴巴所有微服务的基本组成部分。 它已在 6000 多个应用程序中使用,涵盖了几乎所有核心电子商务场景。2018 年,sentinel 演变为一个开源项目。2020 年,sentinel golang 发布。

特点 :

丰富的应用场景 :sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即

突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。

完备的实时监控 :sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机

器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。

* 生态广广泛 *

sentinel 的历史

2012 年,sentinel 诞生,主要功能为入口流量控制。

2013-2017 年,sentinel 在阿里巴巴集团内部迅速发展,成为基础技术模块,覆盖了所有的核心场景。sentinel 也因此积累了大量的流量归整场景以及生产实践。

2018 年,sentinel 开源,并持续演进。

2019 年,sentinel 朝着多语言扩展的方向不断探索,推出 c 原生版本,同时针对 service mesh 场景也推出了 envoy 集群流量控制支持,以解决 service mesh 架构下多语言限流的问题。

2020 年,推出 sentinel go 版本,继续朝着云原生方向演进。

2021 年,sentinel 正在朝着 2.0 云原生高可用决策中心组件进行演进;同时推出了 sentinel rust 原生版本。同时我们也在 rust 社区进行了 envoy wasm extension 及 ebpf extension 等场景探索。

2022 年,sentinel 品牌升级为流量治理,领域涵盖流量路由 / 调度、流量染色、流控降级、过载保护 / 实例摘除等;同时社区将流量治理相关标准抽出到 opensergo 标准中,sentinel 作为流量治理标准实现。

sentinel-go 的安装

sentinel-go 开源地址:https://github.com/alibaba/sentinel-golang

ag真人官方网官网文档

安装:go get github.com/alibaba/sentinel-golang/api

go 限流实战

qps 限流

package mainimport (    "fmt"    "log"    sentinel "github.com/alibaba/sentinel-golang/api"    "github.com/alibaba/sentinel-golang/core/base"    "github.com/alibaba/sentinel-golang/core/flow")func main() {    //基于sentinel的qps限流    //必须初始化    err := sentinel.initdefault()    if err != nil {        log.fatalf("unexpected error: % v", err)    }    //配置限流规则:1秒内通过10次    _, err = flow.loadrules([]*flow.rule{        {            resource:               "some_test",            tokencalculatestrategy: flow.direct,            controlbehavior:        flow.reject, //超过直接拒绝            threshold:              10,          //请求次数            statintervalinms:       1000,        //允许时间内        },    })    if err != nil {        log.fatalf("unexpected error: % v", err)        return    }    for i := 0; i < 12; i   {        e, b := sentinel.entry("some_test", sentinel.withtraffictype(base.inbound))        if b != nil {            fmt.println("限流了")        } else {            fmt.println("检查通过")            e.exit()        }    }}

打印结果:

检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过限流了限流了

thrnotting

package mainimport (    "fmt"    "log"    "time"    sentinel "github.com/alibaba/sentinel-golang/api"    "github.com/alibaba/sentinel-golang/core/base"    "github.com/alibaba/sentinel-golang/core/flow")func main() {    //基于sentinel的qps限流    //必须初始化    err := sentinel.initdefault()    if err != nil {        log.fatalf("unexpected error: % v", err)    }    //配置限流规则    _, err = flow.loadrules([]*flow.rule{        {            resource:               "some_test",            tokencalculatestrategy: flow.direct,            controlbehavior:        flow.throttling, //匀速通过            threshold:              10,              //请求次数            statintervalinms:       1000,            //允许时间内        },    })    if err != nil {        log.fatalf("unexpected error: % v", err)        return    }    for i := 0; i < 12; i   {        e, b := sentinel.entry("some_test", sentinel.withtraffictype(base.inbound))        if b != nil {            fmt.println("限流了")        } else {            fmt.println("检查通过")            e.exit()        }        time.sleep(time.millisecond * 100)    }}
检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过检查通过

warrm_up

package mainimport (    "fmt"    "log"    "math/rand"    "time"    sentinel "github.com/alibaba/sentinel-golang/api"    "github.com/alibaba/sentinel-golang/core/base"    "github.com/alibaba/sentinel-golang/core/flow")func main() {    //先初始化sentinel    err := sentinel.initdefault()    if err != nil {        log.fatalf("初始化sentinel 异常: %v", err)    }    var globaltotal int    var passtotal int    var blocktotal int    ch := make(chan struct{})    //配置限流规则    _, err = flow.loadrules([]*flow.rule{        {            resource:               "some-test",            tokencalculatestrategy: flow.warmup, //冷启动策略            controlbehavior:        flow.reject, //直接拒绝            threshold:              1000,            warmupperiodsec:        30,        },    })    if err != nil {        log.fatalf("加载规则失败: %v", err)    }    //我会在每一秒统计一次,这一秒只能 你通过了多少,总共有多少, block了多少, 每一秒会产生很多的block    for i := 0; i < 100; i   {        go func() {            for {                globaltotal                  e, b := sentinel.entry("some-test", sentinel.withtraffictype(base.inbound))                if b != nil {                    //fmt.println("限流了")                    blocktotal                      time.sleep(time.duration(rand.uint64()) * time.millisecond)                } else {                    passtotal                      time.sleep(time.duration(rand.uint64()) * time.millisecond)                    e.exit()                }            }        }()    }    go func() {        var oldtotal int //过去1s总共有多少个        var oldpass int  //过去1s总共pass多少个        var oldblock int //过去1s总共block多少个        for {            onesecondtotal := globaltotal - oldtotal            oldtotal = globaltotal            onesecondpass := passtotal - oldpass            oldpass = passtotal            onesecondblock := blocktotal - oldblock            oldblock = blocktotal            time.sleep(time.second)            fmt.printf("total:%d, pass:%d, block:%d\n", onesecondtotal, onesecondpass, onesecondblock)        }    }()    <-ch}

打印结果:逐渐到达 1k, 在 1k 位置上下波动

total:11, pass:9, block:0total:21966, pass:488, block:21420total:21793, pass:339, block:21414total:21699, pass:390, block:21255total:21104, pass:393, block:20654total:21363, pass:453, block:20831total:21619, pass:491, block:21052total:21986, pass:533, block:21415total:21789, pass:594, block:21123total:21561, pass:685, block:20820total:21663, pass:873, block:20717total:20904, pass:988, block:19831total:21500, pass:996, block:20423total:21769, pass:1014, block:20682total:20893, pass:1019, block:19837total:21561, pass:973, block:20524total:21601, pass:1014, block:20517total:21475, pass:993, block:20420total:21457, pass:983, block:20418total:21397, pass:1024, block:20320total:21690, pass:996, block:20641total:21526, pass:991, block:20457total:21779, pass:1036, block:20677

go 熔断实战

这里我们介绍一个错误数量的,查看详细熔断机制

error_countpackage mainimport (    "errors"    "fmt"    "log"    "math/rand"    "time"    sentinel "github.com/alibaba/sentinel-golang/api"    "github.com/alibaba/sentinel-golang/core/circuitbreaker"    "github.com/alibaba/sentinel-golang/core/config"    "github.com/alibaba/sentinel-golang/logging"    "github.com/alibaba/sentinel-golang/util")type statechangetestlistener struct {}func (s *statechangetestlistener) ontransformtoclosed(prev circuitbreaker.state, rule circuitbreaker.rule) {    fmt.printf("rule.steategy: % v, from %s to closed, time: %d\n", rule.strategy, prev.string(), util.currenttimemillis())}func (s *statechangetestlistener) ontransformtoopen(prev circuitbreaker.state, rule circuitbreaker.rule, snapshot interface{}) {    fmt.printf("rule.steategy: % v, from %s to open, snapshot: %d, time: %d\n", rule.strategy, prev.string(), snapshot, util.currenttimemillis())}func (s *statechangetestlistener) ontransformtohalfopen(prev circuitbreaker.state, rule circuitbreaker.rule) {    fmt.printf("rule.steategy: % v, from %s to half-open, time: %d\n", rule.strategy, prev.string(), util.currenttimemillis())}func main() {    //基于连接数的降级模式    total := 0    totalpass := 0    totalblock := 0    totalerr := 0    conf := config.newdefaultconfig()    // for testing, logging output to console    conf.sentinel.log.logger = logging.newconsolelogger()    err := sentinel.initwithconfig(conf)    if err != nil {        log.fatal(err)    }    ch := make(chan struct{})    // register a state change listener so that we could observer the state change of the internal circuit breaker.    circuitbreaker.registerstatechangelisteners(&statechangetestlistener{})    _, err = circuitbreaker.loadrules([]*circuitbreaker.rule{        // statistic time span=10s, recoverytimeout=3s, maxerrorcount=50        {            resource:         "abc",            strategy:         circuitbreaker.errorcount,            retrytimeoutms:   3000, //3s只有尝试回复            minrequestamount: 10,   //静默数            statintervalms:   5000,            threshold:        50,        },    })    if err != nil {        log.fatal(err)    }    logging.info("[circuitbreaker errorcount] sentinel go circuit breaking demo is running. you may see the pass/block metric in the metric log.")    go func() {        for {            total              e, b := sentinel.entry("abc")            if b != nil {                // g1 blocked                totalblock                  fmt.println("协程熔断了")                time.sleep(time.duration(rand.uint64() ) * time.millisecond)            } else {                totalpass                  if rand.uint64()  > 9 {                    totalerr                      // record current invocation as error.                    sentinel.traceerror(e, errors.new("biz error"))                }                // g1 passed                time.sleep(time.duration(rand.uint64()  10) * time.millisecond)                e.exit()            }        }    }()    go func() {        for {            total              e, b := sentinel.entry("abc")            if b != nil {                // g2 blocked                totalblock                  time.sleep(time.duration(rand.uint64() ) * time.millisecond)            } else {                // g2 passed                totalpass                  time.sleep(time.duration(rand.uint64()�) * time.millisecond)                e.exit()            }        }    }()    go func() {        for {            time.sleep(time.second)            fmt.println(totalerr)        }    }()    <-ch}

以上就是什么是限流和熔断?详解sentinel限流熔断降级的详细内容,更多请关注php中文网其它相关文章!

关键词:

ag真人官方网 ag真人官方网的版权所有.

联系网站:920 891 263@qq.com
网站地图