File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ package service_load_balancing
2
+
3
+ import (
4
+ "math/rand"
5
+ "testing"
6
+ "time"
7
+ )
8
+
9
+ var endpoints = []string {
10
+ "127.0.0.1:80" ,
11
+ "127.0.0.2:80" ,
12
+ "127.0.0.3:80" ,
13
+ "127.0.0.4:80" ,
14
+ "127.0.0.5:80" ,
15
+ "127.0.0.6:80" ,
16
+ "127.0.0.7:80" ,
17
+ }
18
+
19
+ //从数学上得到过证明的还是经典的fisher-yates算法,主要思路为每次随机挑选一个值,放在数组末尾。然后在n-1个元素的数组中再随机挑选一个值,放在数组末尾,以此类推。
20
+ func fisher_yates (slice []int ) {
21
+ rand .Seed (time .Now ().UnixNano ())
22
+ for i := len (slice ); i > 0 ; i -- {
23
+ lastIdx := i - 1
24
+ idx := rand .Intn (i )
25
+ slice [lastIdx ], slice [idx ] = slice [idx ], slice [lastIdx ]
26
+ }
27
+ }
28
+
29
+ func TestShuffle (t * testing.T ) {
30
+ var indexArray = make ([]int , 0 , len (endpoints ))
31
+ for i := 0 ; i < len (endpoints ); i ++ {
32
+ indexArray = append (indexArray , i )
33
+ }
34
+ t .Log ("索引数组" , indexArray )
35
+ for i := 0 ; i < 10 ; i ++ {
36
+ fisher_yates (indexArray )
37
+ t .Log ("fisher_yates 后选择的负载均衡节点信息" , endpoints [indexArray [0 ]])
38
+
39
+ }
40
+
41
+ }
You can’t perform that action at this time.
0 commit comments