circuitbreaker

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package circuitbreaker 提供熔断器原语:当下游错误率超过阈值时自动"断开"保护调用方, 经过冷却期后进入半开探测,探测成功则恢复、失败则继续断开。

三态:Closed(正常) → Open(熔断,快速失败) → HalfOpen(探测) → Closed / Open。 错误率用固定窗口(ring bucket)统计;Open 期间 Do 立即返回 ErrCircuitOpen。

与 beauty 弹性三件套互补:

  • backoff:退避计算(延迟多久)
  • hedge:对冲请求(备份并发)
  • ratelimit:限速率(每秒多少)
  • circuitbreaker:熔断(错误率过高时切断)

纯标准库、并发安全。

Index

Constants

This section is empty.

Variables

View Source
var ErrCircuitOpen = errors.New("circuitbreaker: circuit open")

ErrCircuitOpen 表示熔断器处于 Open 状态,请求被快速失败。

Functions

This section is empty.

Types

type Breaker

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

Breaker 是一个熔断器实例。并发安全。

func New

func New(opts ...Option) *Breaker

New 创建熔断器。

func (*Breaker) Do

func (b *Breaker) Do(fn func() error) error

Do 包装一次调用:Closed 正常执行并统计;Open 快速失败;HalfOpen 执行探测。 fn 返回 error 视为失败;返回 nil 视为成功。

func (*Breaker) Failures

func (b *Breaker) Failures() int64

Failures 返回当前窗口失败数。

func (*Breaker) State

func (b *Breaker) State() State

State 返回当前状态。

func (*Breaker) Successes

func (b *Breaker) Successes() int64

Successes 返回当前窗口成功数(仅 Closed 态有效)。

type Option

type Option func(*config)

Option 配置 Breaker。

func WithCooldown

func WithCooldown(d time.Duration) Option

WithCooldown 设置 Open 状态冷却期(默认 5s),到期后进入 HalfOpen。

func WithHalfOpenMax

func WithHalfOpenMax(n int) Option

WithHalfOpenMax 设置半开期最多放过的探测请求数(默认 3)。全部成功则关闭;任一失败重新 Open。

func WithMinRequests

func WithMinRequests(n int) Option

WithMinRequests 设置触发熔断的最少请求数(默认 10),窗口内不够则不判定。

func WithOnStateChange

func WithOnStateChange(fn func(from, to State)) Option

WithOnStateChange 注册状态变化回调(用于日志/埋点)。

func WithThreshold

func WithThreshold(rate float64) Option

WithThreshold 设置错误率阈值(默认 0.5 即 50%)。

func WithWindow

func WithWindow(d time.Duration) Option

WithWindow 设置统计窗口(默认 10s)。

type State

type State int

State 是熔断器当前状态。

const (
	StateClosed   State = iota // 正常放行,统计错误率
	StateOpen                  // 熔断,快速失败
	StateHalfOpen              // 半开,允许少量探测
)

func (State) String

func (s State) String() string

Jump to

Keyboard shortcuts

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