circuit

package
v1.42.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package circuit 提供熔断器(参考 gobreaker/业界通用设计):

closed(正常) → open(熔断) → half-open(试探) → closed(恢复)

用于保护对第三方/下游服务的调用:失败率达到阈值时快速失败, 避免故障扩散(雪崩);冷却期后放行试探请求,成功即恢复。

与 thirdparty 客户端集成:

client := thirdparty.NewClient(thirdparty.Config{
    BaseURL: "https://sms.partner.com",
    Signer:  thirdparty.NewHMACSigner("key", "secret"),
    Breaker: circuit.New(circuit.DefaultConfig()), // 熔断保护
})

Index

Constants

This section is empty.

Variables

View Source
var ErrOpen = errors.New("circuit breaker is open")

ErrOpen 熔断器打开时快速失败返回的错误。

Functions

This section is empty.

Types

type Breaker

type Breaker struct {
	// contains filtered or unexported fields
}

Breaker 熔断器(并发安全)。

func New

func New(config Config) *Breaker

New 创建熔断器;config 零值时使用默认配置。

func (*Breaker) Execute

func (b *Breaker) Execute(fn func() error, classify func(err error) bool) error

Execute 执行受熔断保护的操作。 classify 决定错误是否计入失败(nil 时 err != nil 即失败; 如 HTTP 4xx 业务错误不应触发熔断,可传入分类函数)。 熔断打开时返回 ErrOpen,不执行 fn。

func (*Breaker) State

func (b *Breaker) State() State

State 返回当前状态。

type Config

type Config struct {
	// FailureThreshold 失败率阈值(0-1):窗口内失败请求占比达到该值触发熔断。
	// 默认 0.5。
	FailureThreshold float64
	// MinRequests 触发评估的最小请求数:窗口内请求数不足时不触发熔断。
	// 默认 10。
	MinRequests int
	// Window 统计窗口时长:每窗口评估一次失败率。
	// 默认 10 秒。
	Window time.Duration
	// Cooldown 熔断打开后保持时长,之后进入半开试探。
	// 默认 10 秒。
	Cooldown time.Duration
	// HalfOpenMaxRequests 半开状态放行的试探请求数。
	// 默认 1。
	HalfOpenMaxRequests int
}

Config 熔断器配置。

func DefaultConfig

func DefaultConfig() Config

DefaultConfig 返回推荐配置(失败率 50%、最小 10 请求、10s 窗口、10s 冷却)。

type State

type State int

State 熔断器状态。

const (
	// StateClosed 关闭:请求正常放行,统计失败率。
	StateClosed State = iota
	// StateOpen 打开:快速失败,不发起真实请求。
	StateOpen
	// StateHalfOpen 半开:放行少量试探请求,判断服务是否恢复。
	StateHalfOpen
)

func (State) String

func (s State) String() string

String 状态名。

type Stats

type Stats struct {
	State       State   `json:"state"`
	Success     int     `json:"success"`
	Failure     int     `json:"failure"`
	FailureRate float64 `json:"failure_rate"`
}

Stats 返回当前统计(诊断/监控用)。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL