Fix: fix rand.Seed() duplicate concurrent calls (#1958)
* fix: fix rand.Seed() duplicate concurrent calls
* fix: fix rand.Seed() in p2c/loadbalance_test.go
diff --git a/cluster/loadbalance/p2c/loadbalance.go b/cluster/loadbalance/p2c/loadbalance.go
index 7a044cc..12f2a37 100644
--- a/cluster/loadbalance/p2c/loadbalance.go
+++ b/cluster/loadbalance/p2c/loadbalance.go
@@ -44,6 +44,7 @@
)
func init() {
+ rand.Seed(randSeed())
extension.SetLoadbalance(constant.LoadBalanceKeyP2C, newP2CLoadBalance)
}
@@ -78,7 +79,6 @@
if len(invokers) == 2 {
i, j = 0, 1
} else {
- rand.Seed(randSeed())
i = rand.Intn(len(invokers))
j = i
for i == j {
diff --git a/cluster/loadbalance/p2c/loadbalance_test.go b/cluster/loadbalance/p2c/loadbalance_test.go
index 17092fb..ff27ed0 100644
--- a/cluster/loadbalance/p2c/loadbalance_test.go
+++ b/cluster/loadbalance/p2c/loadbalance_test.go
@@ -18,6 +18,7 @@
package p2c
import (
+ "math/rand"
"testing"
)
@@ -37,16 +38,18 @@
func TestLoadBalance(t *testing.T) {
lb := newP2CLoadBalance()
invocation := protoinvoc.NewRPCInvocation("TestMethod", []interface{}{}, nil)
- randSeed = func() int64 {
+ randSeed := func() int64 {
return 0
}
t.Run("no invokers", func(t *testing.T) {
+ rand.Seed(randSeed())
ivk := lb.Select([]protocol.Invoker{}, invocation)
assert.Nil(t, ivk)
})
t.Run("one invoker", func(t *testing.T) {
+ rand.Seed(randSeed())
url0, _ := common.NewURL("dubbo://192.168.1.0:20000/com.ikurento.user.UserProvider")
ivkArr := []protocol.Invoker{
@@ -57,6 +60,7 @@
})
t.Run("two invokers", func(t *testing.T) {
+ rand.Seed(randSeed())
ctrl := gomock.NewController(t)
defer ctrl.Finish()
@@ -86,6 +90,7 @@
})
t.Run("multiple invokers", func(t *testing.T) {
+ rand.Seed(randSeed())
ctrl := gomock.NewController(t)
defer ctrl.Finish()
@@ -117,6 +122,7 @@
})
t.Run("metrics i not found", func(t *testing.T) {
+ rand.Seed(randSeed())
ctrl := gomock.NewController(t)
defer ctrl.Finish()
@@ -144,6 +150,7 @@
})
t.Run("metrics j not found", func(t *testing.T) {
+ rand.Seed(randSeed())
ctrl := gomock.NewController(t)
defer ctrl.Finish()
diff --git a/registry/servicediscovery/instance/random/random_service_instance_selector.go b/registry/servicediscovery/instance/random/random_service_instance_selector.go
index 599fb4d..82dbe85 100644
--- a/registry/servicediscovery/instance/random/random_service_instance_selector.go
+++ b/registry/servicediscovery/instance/random/random_service_instance_selector.go
@@ -30,6 +30,7 @@
)
func init() {
+ rand.Seed(time.Now().UnixNano())
extension.SetServiceInstanceSelector("random", NewRandomServiceInstanceSelector)
}
@@ -47,7 +48,6 @@
if len(serviceInstances) == 1 {
return serviceInstances[0]
}
- rand.Seed(time.Now().UnixNano())
index := rand.Intn(len(serviceInstances))
return serviceInstances[index]
}