yumosx commented on code in PR #3046:
URL: https://github.com/apache/dubbo-go/pull/3046#discussion_r2510876376
##########
cluster/loadbalance/p2c/loadbalance.go:
##########
@@ -37,28 +37,65 @@ import (
"dubbo.apache.org/dubbo-go/v3/protocol/base"
)
-var (
- randSeed = func() int64 {
- return time.Now().Unix()
- }
-)
-
func init() {
- rand.Seed(randSeed())
- extension.SetLoadbalance(constant.LoadBalanceKeyP2C, newP2CLoadBalance)
+ extension.SetLoadbalance(constant.LoadBalanceKeyP2C, func()
loadbalance.LoadBalance {
+ return newP2CLoadBalance(nil)
+ })
}
var (
once sync.Once
instance loadbalance.LoadBalance
)
-type p2cLoadBalance struct{}
+// p2cLoadBalance is a load balancer implementation based on the Power of Two
Choices algorithm.
+type p2cLoadBalance struct {
+ // randomPicker is injectable for testing; allows deterministic random
selection.
+ randomPicker randomPicker
+}
+
+// randomPicker is a function type that randomly selects two distinct indices
from a range [0, n).
+// This function type is designed ONLY FOR TEST purposes to inject predictable
values.
+type randomPicker func(n int) (i, j int)
+
+var rndPool = sync.Pool{
+ New: func() any {
+ return rand.New(rand.NewSource(time.Now().Unix()))
+ },
+}
+
+// defaultRnd is the default implementation of randomPicker.
+// It handles edge cases for n <= 2 and ensures two distinct random indices
for n > 2.
+func defaultRnd(n int) (i, j int) {
+ if n <= 1 {
+ return 0, 0
+ }
+ if n == 2 {
+ return 0, 1
+ }
+
+ rnd := rndPool.Get().(*rand.Rand)
+ defer rndPool.Put(rnd)
-func newP2CLoadBalance() loadbalance.LoadBalance {
+ i = rnd.Intn(n) // NOSONAR
+ j = rnd.Intn(n) // NOSONAR
+ for i == j {
+ j = rand.Intn(n) // NOSONAR
Review Comment:
done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]