WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed
Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ package circuitbreaker
2+
3+ import (
4+ "github.com/go-kratos/aegis/internal/syncmap"
5+ )
6+
7+ // CircuitBreakerFactory 定义一个闭包类型,用于创建 CircuitBreaker 实例
8+ type CircuitBreakerFactory func () CircuitBreaker
9+
10+ // Group is a circuit breaker that manages multiple circuit breakers by key.
11+ type Group struct {
12+ requests syncmap.SyncMap [string , CircuitBreaker ]
13+ cbFactory CircuitBreakerFactory
14+ }
15+
16+ // NewGroupCircuitBreaker creates a new Group with the given factory.
17+ func NewGroup (factory CircuitBreakerFactory ) * Group {
18+ g := & Group {
19+ cbFactory : factory ,
20+ }
21+ return g
22+ }
23+
24+ // GetCircuitBreaker returns a CircuitBreaker for the given key.
25+ func (g * Group ) GetCircuitBreaker (key string ) CircuitBreaker {
26+ cb , ok := g .requests .Load (key )
27+ if ! ok {
28+ // 使用传入的闭包创建具体的 CircuitBreaker 实例
29+ cb , _ = g .requests .LoadOrStore (key , g .cbFactory ())
30+ }
31+ return cb
32+ }
Original file line number Diff line number Diff line change 1+ package circuitbreaker_test
2+
3+ import (
4+ "testing"
5+
6+ "github.com/go-kratos/aegis/circuitbreaker"
7+ "github.com/go-kratos/aegis/circuitbreaker/sre"
8+ "github.com/stretchr/testify/assert"
9+ )
10+
11+ func TestGroup_GetCircuitBreaker (t * testing.T ) {
12+ g := circuitbreaker .NewGroup (func () circuitbreaker.CircuitBreaker {
13+ return sre .NewBreaker ()
14+ })
15+ succ := g .GetCircuitBreaker ("succ" )
16+ assert .NotNil (t , succ )
17+ fail := g .GetCircuitBreaker ("fail" )
18+ assert .NotNil (t , fail )
19+ markSuccess (succ , 100 )
20+ markFailed (fail , 10000 )
21+ assert .Equal (t , succ .Allow (), nil )
22+ assert .NotEqual (t , fail .Allow (), nil )
23+ }
24+ func markSuccess (cb circuitbreaker.CircuitBreaker , count int ) {
25+ for i := 0 ; i < count ; i ++ {
26+ cb .MarkSuccess ()
27+ }
28+ }
29+ func markFailed (cb circuitbreaker.CircuitBreaker , count int ) {
30+ for i := 0 ; i < count ; i ++ {
31+ cb .MarkFailed ()
32+ }
33+ }
You can’t perform that action at this time.
0 commit comments