Skip to content

Commit

Permalink
gee-rpc/day7 use d.index to mode n to ensure safety
Browse files Browse the repository at this point in the history
  • Loading branch information
geektutu committed Oct 6, 2020
1 parent 57e2881 commit b5646b6
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
2 changes: 2 additions & 0 deletions gee-rpc/day7-registry/registry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package registy
import (
"log"
"net/http"
"sort"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -54,6 +55,7 @@ func (r *Registry) aliveServers() []string {
delete(r.servers, addr)
}
}
sort.Strings(alive)
return alive
}

Expand Down
9 changes: 5 additions & 4 deletions gee-rpc/day7-registry/xclient/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,16 @@ func (d *MultiServersDiscovery) Update(servers []string) error {
func (d *MultiServersDiscovery) Get(mode SelectMode) (string, error) {
d.mu.Lock()
defer d.mu.Unlock()
if len(d.servers) == 0 {
n := len(d.servers)
if n == 0 {
return "", errors.New("rpc discovery: no available servers")
}
switch mode {
case RandomSelect:
return d.servers[d.r.Intn(len(d.servers))], nil
return d.servers[d.r.Intn(n)], nil
case RoundRobinSelect:
s := d.servers[d.index]
d.index = (d.index + 1) % len(d.servers)
s := d.servers[d.index%n] // servers could be updated, so mode n to ensure safety
d.index = (d.index + 1) % n
return s, nil
default:
return "", errors.New("rpc discovery: not supported select mode")
Expand Down

0 comments on commit b5646b6

Please sign in to comment.