mirror of
https://github.com/bolucat/Archive.git
synced 2025-12-24 13:28:37 +08:00
Update On Sun Jul 21 20:29:04 CEST 2024
This commit is contained in:
@@ -1,46 +0,0 @@
|
||||
package lb
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go.uber.org/atomic"
|
||||
)
|
||||
|
||||
// todo: move to internal/lb
|
||||
type Node struct {
|
||||
Address string
|
||||
Label string
|
||||
HandShakeDuration time.Duration
|
||||
}
|
||||
|
||||
func (n *Node) Clone() *Node {
|
||||
return &Node{
|
||||
Address: n.Address,
|
||||
Label: n.Label,
|
||||
HandShakeDuration: n.HandShakeDuration,
|
||||
}
|
||||
}
|
||||
|
||||
// RoundRobin is an interface for representing round-robin balancing.
|
||||
type RoundRobin interface {
|
||||
Next() *Node
|
||||
}
|
||||
|
||||
type roundrobin struct {
|
||||
nodeList []*Node
|
||||
next *atomic.Int64
|
||||
|
||||
len int
|
||||
}
|
||||
|
||||
func NewRoundRobin(nodeList []*Node) RoundRobin {
|
||||
len := len(nodeList)
|
||||
next := atomic.NewInt64(0)
|
||||
return &roundrobin{nodeList: nodeList, len: len, next: next}
|
||||
}
|
||||
|
||||
func (r *roundrobin) Next() *Node {
|
||||
n := r.next.Add(1)
|
||||
next := r.nodeList[(int(n)-1)%r.len]
|
||||
return next
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package lb
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_roundrobin_Next(t *testing.T) {
|
||||
remotes := []string{
|
||||
"127.0.0.1",
|
||||
"127.0.0.2",
|
||||
}
|
||||
nodeList := make([]*Node, len(remotes))
|
||||
for i := range remotes {
|
||||
nodeList[i] = &Node{Address: remotes[i]}
|
||||
}
|
||||
rb := NewRoundRobin(nodeList)
|
||||
|
||||
// normal round robin, should return node one by one
|
||||
for i := 0; i < len(remotes); i++ {
|
||||
if node := rb.Next(); node.Address != remotes[i] {
|
||||
t.Fatalf("need %s got %s", remotes[i], node.Address)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user