go-zero/core/queue/balancedpusher.go

45 lines
786 B
Go
Raw Normal View History

2020-08-13 17:00:53 +08:00
package queue
import (
"errors"
"sync/atomic"
"github.com/tal-tech/go-zero/core/logx"
)
var ErrNoAvailablePusher = errors.New("no available pusher")
2020-08-16 23:07:21 +08:00
type BalancedPusher struct {
2020-08-13 17:00:53 +08:00
name string
pushers []Pusher
index uint64
}
2020-08-16 23:07:21 +08:00
func NewBalancedPusher(pushers []Pusher) Pusher {
return &BalancedPusher{
2020-08-13 17:00:53 +08:00
name: generateName(pushers),
pushers: pushers,
}
}
2020-08-16 23:07:21 +08:00
func (pusher *BalancedPusher) Name() string {
2020-08-13 17:00:53 +08:00
return pusher.name
}
2020-08-16 23:07:21 +08:00
func (pusher *BalancedPusher) Push(message string) error {
2020-08-13 17:00:53 +08:00
size := len(pusher.pushers)
for i := 0; i < size; i++ {
index := atomic.AddUint64(&pusher.index, 1) % uint64(size)
target := pusher.pushers[index]
if err := target.Push(message); err != nil {
logx.Error(err)
} else {
return nil
}
}
return ErrNoAvailablePusher
}