From b5646b692b826689034b9b5988378c307b84c1f7 Mon Sep 17 00:00:00 2001 From: gzdaijie Date: Tue, 6 Oct 2020 19:38:27 +0800 Subject: [PATCH] gee-rpc/day7 use d.index to mode n to ensure safety --- gee-rpc/day7-registry/registry/registry.go | 2 ++ gee-rpc/day7-registry/xclient/discovery.go | 9 +++++---- 2 files changed, 7 insertions(+), 4 deletions(-) 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")