diff --git a/gee-rpc/day7-registry/registry/registry.go b/gee-rpc/day7-registry/registry/registry.go index 0d50b4d..2c22244 100644 --- a/gee-rpc/day7-registry/registry/registry.go +++ b/gee-rpc/day7-registry/registry/registry.go @@ -3,6 +3,7 @@ package registy import ( "log" "net/http" + "sort" "strings" "sync" "time" @@ -54,6 +55,7 @@ func (r *Registry) aliveServers() []string { delete(r.servers, addr) } } + sort.Strings(alive) return alive } diff --git a/gee-rpc/day7-registry/xclient/discovery.go b/gee-rpc/day7-registry/xclient/discovery.go index f823a7b..783ec4a 100644 --- a/gee-rpc/day7-registry/xclient/discovery.go +++ b/gee-rpc/day7-registry/xclient/discovery.go @@ -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")