golang框架如何通过限流和熔断提高系统的并发能力?

2024-08-11 0 679

golang 框架通过限流和熔断提升并发能力,具体实现如下:限流:限制每秒请求数量,防止系统超负荷,实现方式为使用令牌桶算法;熔断:当系统故障时暂停处理请求,防止故障传播,实现方式为使用断路器模式,设置最大失败次数、打开时间和复位时间。

golang框架如何通过限流和熔断提高系统的并发能力?

Golang 框架如何通过限流和熔断提高系统的并发能力

限流

限流是一种用来限制系统每秒钟处理请求数量的技术。它可以防止系统超负荷,从而导致性能下降或崩溃。在 Golang 中,可以使用以下代码段来实现限流:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

import (

    "context"

    "errors"

    "time"

)

// limit is a struct that implements the Token Bucket algorithm

type Limit struct {

    rate  time.Duration

    burst int

    queue chan struct{}

    ctx   context.Context

    cancel context.CancelFunc

}

// NewLimit creates a new Limit

func NewLimit(rate time.Duration, burst int) *Limit {

    ctx, cancel := context.WithCancel(context.Background())

    return &Limit{

        rate:  rate,

        burst: burst,

        queue: make(chan struct{}, burst),

        ctx:   ctx,

        cancel: cancel,

    }

}

// Wait waits for a token to become available and then consumes it

func (l *Limit) Wait() error {

    select {

    case <-l.ctx.Done():

        return errors.New("context canceled")

    case <-l.queue:

        return nil

    }

}

// Acquire acquires a token and increments the counter

func (l *Limit) Acquire() error {

    if err := l.Wait(); err != nil {

        return err

    }

    go func() {

        time.Sleep(l.rate)

        select {

        case l.queue <- struct{}{}:

        case <-l.ctx.Done():

        }

    }()

    return nil

}

熔断

立即学习“go语言免费学习笔记(深入)”;

熔断是一种当系统出现故障时暂时停止处理请求的技术。它可以防止故障传播并允许系统自我恢复。在 Golang 中,可以使用以下代码段来实现熔断:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

import (

    "context"

    "sync/atomic"

    "time"

)

// CircuitBreaker is a struct that implements the Circuit Breaker pattern

type CircuitBreaker struct {

    maxFailures    int

    openTime       time.Duration

    resetTime      time.Duration

    count          int64

    state          string

    openAt         time.Time

    resetAt        time.Time

    closEDAt       time.Time

    lastFailedAt   time.Time

    totalFailures  int64

    totalsuccesses int64

}

// NewCircuitBreaker creates a new CircuitBreaker

func NewCircuitBreaker(maxFailures int, openTime time.Duration, resetTime time.Duration) *CircuitBreaker {

    return &CircuitBreaker{

        maxFailures: maxFailures,

        openTime:    openTime,

        resetTime:   resetTime,

        state:       "CLOSED",

        closedAt:    time.now(),

    }

}

// Execute executes a function and handles circuit breaker logic

func (cb *CircuitBreaker) Execute(f func()) {

    switch cb.state {

    case "OPEN":

        if time.Since(cb.openAt) > cb.openTime {

            cb.setState("HALF_OPEN")

            cb.openAt = time.Now()

        }

        return

    case "HALF_OPEN":

        if time.Since(cb.resetAt) > cb.resetTime {

            cb.setState("CLOSED")

            cb.resetAt = time.Now()

        }

    }

    start := time.Now()

    f()

    end := time.Since(start)

    if end >= cb.openTime {

        atomic.AddInt64(&cb.count, 1)

    } else {

        atomic.AddInt64(&cb.totalSuccesses, 1)

    }

    if atomic.LoadInt64(&cb.count) >= int64(maxFailures) {

        cb.setState("OPEN")

        cb.count = 0

    }

}

// setState changes the state of the circuit breaker

func (cb *CircuitBreaker) setState(state string) {

    switch state {

    case "OPEN":

        cb.state = "OPEN"

        cb.openAt = time.Now()

    case "HALF_OPEN":

        cb.state = "HALF_OPEN"

        cb.resetAt = time.Now()

    case "CLOSED":

        cb.state = "CLOSED"

        cb.closedAt = time.Now()

    }

}

实战案例

以下是一个使用限流和熔断来提高 Golang 应用并发能力的实战案例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

import (

    "context"

    "fmt"

    "log"

    "net/HTTP"

    "sync"

    "time"

    "Github.com/google/go-github/v42/github"

)

// Limit the number of requests to the GitHub API

var rateLimiter = NewLimit(time.Second, 10)

// Circuit breaker to prevent overloading the GitHub API

var cb = NewCircuitBreaker(3, time.Minute, time.Minute*5)

func main() {

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        if err := acquireToken(); err != nil {

            // Handle error

            return

        }

        cb.Execute(func() {

            // Make request to GitHub API

            client := github.NewClient(nil)

            ctx := context.Background()

            repos, _, err := client.Repositories.List(ctx, "", nil)

            if err != nil {

                // Handle error

                return

            }

            for _, repo := range repos {

                fmt.Fprintf(w, "%s\n", repo.GetFullName())

            }

        })

    })

    log.Fatal(http.ListeNANDServe(":8080", nil))

}

// acquireToken blocks until a token is available and then consumes it

func acquireToken() error {

    if err := rateLimiter.Acquire(); err != nil {

        return err

    }

    return nil

}

在这个示例中,rateLimiter 用于限制对 GitHub API 的请求速率,而 cb 则用于防止因故障导致请求过载。这使得应用程序能够以受控和健壮的方式处理来自用户的请求,从而提高了系统的整体并发能力。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

免责声明
1. 本站所有资源来源于用户上传和网络等,如有侵权请邮件联系本站整改team@lcwl.fun!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系本站工作人员处理!
6. 本站资源售价或VIP只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 因人力时间成本问题,部分源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别!
9.本站所有源码资源都是经过本站工作人员人工亲测可搭建的,保证每个源码都可以正常搭建,但不保证源码内功能都完全可用,源码属于可复制的产品,无任何理由退款!

网站搭建学习网 Go golang框架如何通过限流和熔断提高系统的并发能力? https://www.xuezuoweb.com/10823.html

常见问题
  • 本站所有的源码都是经过平台人工部署搭建测试过可用的
查看详情
  • 购买源码资源时购买了带主机的套餐是指可以享受源码和所选套餐型号的主机两个产品,在本站套餐里开通主机可享优惠,最高免费使用主机
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

Fa快捷助手
手机编程软件开发

在手机上用手点一点就能轻松做软件

去做软件
链未云主机
免备案香港云主机

开通主机就送域名的免备案香港云主机

去使用
链未云服务器
免备案香港云服务器

支持售后、超低价、稳定的免备案香港云服务器

去使用