Announcement

👇Official Account👇

Welcome to join the group & private message

Article first/tail QR code

Skip to content

Lesson 4.5: 服务治理

学习目标

  • 掌握微服务治理的核心模式

1. 治理模式对比

模式目的Go 常用库
熔断防止级联故障gobreaker
降级提供降级响应手动实现
限流保护自身资源rate (golang.org/x/time)
重试容忍临时故障手动 / backoff
超时避免等待堆积context.WithTimeout

熔断器示例

go
import "github.com/sony/gobreaker"

cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{
    Name:        "user-service",
    MaxRequests: 3,          // 半开后最多放行 3 个请求
    Interval:    60 * time.Second,
    Timeout:     30 * time.Second,  // 半开等待时间
    ReadyToTrip: func(counts gobreaker.Counts) bool {
        failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
        return counts.Requests >= 3 && failureRatio >= 0.6
    },
})

body, err := cb.Execute(func() (interface{}, error) {
    return http.Get("http://user-service/api/users")
})

推荐阅读

上次更新于: