熔斷器中間件,用于提供客戶端熔斷功能,默認(rèn)實(shí)現(xiàn)了sre breaker 算法。
WithGroup
?breaker 依賴于 ?container/group
? 來實(shí)現(xiàn)對(duì)于針對(duì)不同 ?Operation
?使用互相獨(dú)立的 breaker。 ?WithGroup
?可以配置自定義的 ?Breaker
?來替換默認(rèn)的熔斷算法:
// WithGroup with circuit breaker group.
// NOTE: implements generics circuitbreaker.CircuitBreaker
func WithGroup(g *group.Group) Option {
return func(o *options) {
o.group = g
}
}
默認(rèn)配置會(huì)針對(duì)不同的 ?Operation
?生成獨(dú)立的 breaker:
opt := &options{
group: group.NewGroup(func() interface{} {
return sre.NewBreaker()
}),
}
group.Group 是一個(gè) 懶加載容器 在本文中裝載進(jìn) group.Group 的實(shí)例,應(yīng)實(shí)現(xiàn) ?aegis/circuitbreaker
? 的 CircuitBreaker 接口。
// CircuitBreaker is a circuit breaker.
type CircuitBreaker interface {
Allow() error // 判斷請(qǐng)求是否允許發(fā)送,如果返回 error 則表示請(qǐng)求被拒絕
MarkSuccess() // 標(biāo)記請(qǐng)求成功
MarkFailed() // 標(biāo)記請(qǐng)求失敗
}
// http
conn, err := http.NewClient(
context.Background(),
http.WithMiddleware(
circuitbreaker.Client(),
),
http.WithEndpoint("127.0.0.1:8000"),
)
// grpc
conn,err := transgrpc.Dial(
context.Background(),
grpc.WithMiddleware(
circuitbreaker.Client(),
),
grpc.WithEndpoint("127.0.0.1:9000"),
)
當(dāng)熔斷器觸發(fā)時(shí),會(huì)在一段時(shí)間內(nèi)對(duì)于該?Operation
?的調(diào)用快速失敗,并返回錯(cuò)誤?ErrNotAllowed
?,定義如下:
// ErrNotAllowed is request failed due to circuit breaker triggered.
var ErrNotAllowed = errors.New(503, "CIRCUITBREAKER", "request failed due to circuit breaker triggered")
更多建議: