diff --git a/raft/node.go b/raft/node.go index d4724301a..10a9c2652 100644 --- a/raft/node.go +++ b/raft/node.go @@ -3,7 +3,9 @@ package raft import ( "encoding/json" golog "log" + "math/rand" "sync/atomic" + "time" ) type Interface interface { @@ -36,9 +38,10 @@ func New(id int64, heartbeat, election tick) *Node { panic("election is least three times as heartbeat [election: %d, heartbeat: %d]") } + rand.Seed(time.Now().UnixNano()) n := &Node{ heartbeat: heartbeat, - election: election, + election: election + tick(rand.Int31())%election, sm: newStateMachine(id, []int64{id}), rmNodes: make(map[int64]struct{}), } diff --git a/raft/node_test.go b/raft/node_test.go index d5a9f3136..1992ff2a3 100644 --- a/raft/node_test.go +++ b/raft/node_test.go @@ -16,7 +16,7 @@ func TestTickMsgHup(t *testing.T) { // simulate to patch the join log n.Step(Message{Type: msgApp, Commit: 1, Entries: []Entry{Entry{}}}) - for i := 0; i < defaultElection+1; i++ { + for i := 0; i < defaultElection*2; i++ { n.Tick() }