option chan length

pull/2481/head
FengbinShi 2 years ago
parent b9acf8fbbf
commit 52b4215510
  1. 24
      health/checker.go
  2. 2
      health/health.go
  3. 21
      health/health_test.go

@ -31,16 +31,18 @@ type checkerHandler struct {
Notifier
}
func NewChecker(name string, ch Checker, interval, timeout time.Duration) CheckerHandler {
return &checkerHandler{
func NewChecker(name string, ch Checker, opt ...CheckOption) CheckerHandler {
c := &checkerHandler{
Name: name,
intervalTime: interval,
timeout: timeout,
Checker: ch,
CheckerStatus: CheckerStatus{},
RWMutex: &sync.RWMutex{},
Notifier: nil,
}
for _, v := range opt {
v(c)
}
return c
}
func (c *checkerHandler) setNotifier(w Notifier) {
@ -104,3 +106,17 @@ func (c *checkerHandler) getStatus() CheckerStatus {
defer c.RUnlock()
return c.CheckerStatus
}
type CheckOption func(handler *checkerHandler)
func WithInterval(interval time.Duration) CheckOption {
return func(handler *checkerHandler) {
handler.intervalTime = interval
}
}
func WithTimeout(timeout time.Duration) CheckOption {
return func(handler *checkerHandler) {
handler.timeout = timeout
}
}

@ -100,7 +100,7 @@ func (c *CheckerMgr) NewWatcher() Watcher {
c.lock.Lock()
wID := c.watcherID
c.watcherID++
ch := make(chan string, 1)
ch := make(chan string, len(c.checkers))
c.watchers[wID] = ch
c.lock.Unlock()
return Watcher{

@ -3,6 +3,7 @@ package health
import (
"fmt"
"golang.org/x/net/context"
"math/rand"
"testing"
"time"
)
@ -12,9 +13,9 @@ type A struct {
func (A) Check(ctx context.Context) (interface{}, error) {
fmt.Println("check A")
//if rand.Int()%2 == 0 {
// return "出错A", fmt.Errorf("错误:%s", "123")
//}
if rand.Int()%5 == 0 {
return "出错A", fmt.Errorf("错误:%s", "123")
}
return "正常A", nil
}
@ -23,25 +24,25 @@ type B struct {
func (B) Check(ctx context.Context) (interface{}, error) {
fmt.Println("check B")
//if rand.Int()%2 == 0 {
// return "出错B", fmt.Errorf("错误:%s", "123B")
//}
if rand.Int()%5 == 0 {
return "出错B", fmt.Errorf("错误:%s", "123B")
}
return "正常B", nil
}
func TestNew(t *testing.T) {
ctx, cancel := context.WithCancel(context.TODO())
cm := New(ctx)
cm.RegisterChecker(NewChecker("A", A{}, time.Second*0, time.Second*10))
cm.RegisterChecker(NewChecker("B", B{}, time.Second*0, time.Second*10))
cm.RegisterChecker(NewChecker("A", A{}, WithInterval(time.Second), WithInterval(time.Second)))
cm.RegisterChecker(NewChecker("B", B{}, WithInterval(time.Second), WithInterval(time.Second)))
cm.Start()
go func() {
w := cm.NewWatcher()
s := cm.GetStatus()
fmt.Println("----", s)
w := cm.NewWatcher()
defer w.Close()
for i := range w.Ch {
fmt.Println("---", cm.GetStatus(i))
fmt.Println("--->>", i, cm.GetStatus(i))
}
}()
time.Sleep(time.Second * 20)

Loading…
Cancel
Save