侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

阿里开源的Sentinel流量治理组件之限流熔断降级等简单示例

Go  /  管理员 发布于 1年前   490

Sentinel是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,

从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。

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

Sentinel流量治理组件.png


官方文档:

https://sentinelguard.io/zh-cn/docs/introduction.html

git官方wiki:

https://github.com/alibaba/Sentinel/wiki

Sentinel-go开源地址:

https://github.com/alibaba/sentinel-golang

官方文档-go语言:

https://sentinelguard.io/zh-cn/docs/golang/quick-start.html


Sentinel-go安装

go get github.com/alibaba/sentinel-golang/api


简单测试限流示例


1.qps限流功能代码示例:

package main

import (
   "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()
       }
   }
}

打印结果:

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


2.Thrnotting(限流)功能代码示例

package main

import (
   "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)
   }
}

打印结果:

检查通过
检查通过
检查通过
检查通过
检查通过
检查通过
检查通过
检查通过
检查通过
检查通过
检查通过
检查通过


3.Warrm_up(降级)

package main

import (
   "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()%10) * time.Millisecond)
           } else {
               passTotal++
               time.Sleep(time.Duration(rand.Uint64()%10) * 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:0
total:21966, pass:488, block:21420
total:21793, pass:339, block:21414
total:21699, pass:390, block:21255
total:21104, pass:393, block:20654
total:21363, pass:453, block:20831
total:21619, pass:491, block:21052
total:21986, pass:533, block:21415
total:21789, pass:594, block:21123
total:21561, pass:685, block:20820
total:21663, pass:873, block:20717
total:20904, pass:988, block:19831
total:21500, pass:996, block:20423
total:21769, pass:1014, block:20682
total:20893, pass:1019, block:19837
total:21561, pass:973, block:20524
total:21601, pass:1014, block:20517
total:21475, pass:993, block:20420
total:21457, pass:983, block:20418
total:21397, pass:1024, block:20320
total:21690, pass:996, block:20641
total:21526, pass:991, block:20457
total:21779, pass:1036, block:20677

分享一个完整的Go熔断实战示例

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

https://sentinelguard.io/zh-cn/docs/golang/circuit-breaking.html

error_count 代码示例

package main

import (
   "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()%20) * time.Millisecond)
} else {
totalPass++
if rand.Uint64()%20 > 9 {
totalErr++
// Record current invocation as error.
sentinel.TraceError(e, errors.New("biz error"))
}
// g1 passed
time.Sleep(time.Duration(rand.Uint64()%20+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()%20) * time.Millisecond)
       } else {
           // g2 passed
           totalPass++
           time.Sleep(time.Duration(rand.Uint64()%80) * time.Millisecond)
           e.Exit()
       }
   }
   }()
   go func() {
       for {
           time.Sleep(time.Second)
           fmt.Println(totalErr)
       }
   }()
   <-ch
}

  • 上一条:
    在go字典树(Trie树)定义与实现方法示例
    下一条:
    在go语言中使用ffmpeg-go库实现截取视频某一帧图片示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    • 2025-05
    • 2025-06
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客