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
Skip to content

Commit ce35296

Browse files
authored
add key circuitbreaker (#48)
* add circuitbreaker group
1 parent dc0144e commit ce35296

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

circuitbreaker/group.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}

circuitbreaker/group_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
}

0 commit comments

Comments
 (0)