parent
7f50406a31
commit
56590829d1
@ -0,0 +1,15 @@
|
|||||||
|
package balancer
|
||||||
|
|
||||||
|
type Balancer interface {
|
||||||
|
NextPeer(nodes interface{}) (error, interface{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBalancer 根据策略标识返回新的负载均衡器
|
||||||
|
func NewBalancer(strategy string) Balancer {
|
||||||
|
switch strategy {
|
||||||
|
case "RoundRobin":
|
||||||
|
return &RoundRobin{}
|
||||||
|
default:
|
||||||
|
return &RoundRobin{}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package balancer
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInputNotSlice = errors.New("Input value is not silice")
|
||||||
|
)
|
@ -0,0 +1,26 @@
|
|||||||
|
package balancer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RoundRobin struct {
|
||||||
|
current uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
// NextPeer 返回轮盘的下一节点
|
||||||
|
func (r *RoundRobin) NextPeer(nodes interface{}) (error, interface{}) {
|
||||||
|
v := reflect.ValueOf(nodes)
|
||||||
|
if v.Kind() != reflect.Slice {
|
||||||
|
return ErrInputNotSlice, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
next := r.NextIndex(v.Len())
|
||||||
|
return nil, v.Index(next).Interface()
|
||||||
|
}
|
||||||
|
|
||||||
|
// NextIndex 返回下一个节点下标
|
||||||
|
func (r *RoundRobin) NextIndex(total int) int {
|
||||||
|
return int(atomic.AddUint64(&r.current, uint64(1)) % uint64(total))
|
||||||
|
}
|
@ -0,0 +1,7 @@
|
|||||||
|
package cluster
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrFeatureNotExist = errors.New("No nodes in nodepool match the feature specificed")
|
||||||
|
)
|
Loading…
Reference in new issue