Skip to content

Commit

Permalink
gee-rpc day6 add robin select for discovery
Browse files Browse the repository at this point in the history
  • Loading branch information
geektutu committed Oct 5, 2020
1 parent 84fe60f commit c66f645
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions gee-rpc/day6-discovery/xclient/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type SelectMode int

const (
RandomSelect SelectMode = iota // select randomly
RobbinSelect // select using Robbin algorithm, not implemented
RobinSelect // select using Robbin algorithm
)

type Discovery interface {
Expand All @@ -26,6 +26,7 @@ type MultiServersDiscovery struct {
r *rand.Rand // generate random number
mu sync.RWMutex // protect following
servers []string
index int // record the selected position for robin algorithm
}

// Update the servers of discovery dynamically if needed
Expand All @@ -36,14 +37,18 @@ func (d *MultiServersDiscovery) Update(servers []string) {
}

func (d *MultiServersDiscovery) Get(mode SelectMode) string {
d.mu.RLock()
defer d.mu.RUnlock()
d.mu.Lock()
defer d.mu.Unlock()
if len(d.servers) == 0 {
return ""
}
switch mode {
case RandomSelect:
return d.servers[d.r.Intn(len(d.servers))]
case RobinSelect:
s := d.servers[d.index]
d.index = (d.index + 1) % len(d.servers)
return s
default:
return ""
}
Expand Down

0 comments on commit c66f645

Please sign in to comment.