-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpersist.go
98 lines (80 loc) · 2.05 KB
/
persist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package raft
import "sync"
// ========== raft 保存的数据 ==========
type RaftState struct {
Term int
VotedFor NodeId
Entries []Entry
}
func (rs RaftState) toHardState(persister RaftStatePersister) HardState {
return HardState{
term: rs.Term,
votedFor: rs.VotedFor,
entries: rs.Entries,
persister: persister,
}
}
// ========== 状态持久化器接口,由用户实现 ==========
type RaftStatePersister interface {
// 每次 raft 的状态改变,都会调用此方法
SaveRaftState(RaftState) error
// 没有时返回空对象
LoadRaftState() (RaftState, error)
}
// ========== 保存的快照数据 ==========
type Snapshot struct {
LastIndex int
LastTerm int
Data []byte
}
// ========== 快照持久化器接口,由用户实现 ==========
type SnapshotPersister interface {
// 保存快照时调用
SaveSnapshot(Snapshot) error
// 若没有需返回空对象
LoadSnapshot() (Snapshot, error)
}
// RaftStatePersister 接口的内存实现,开发测试用
type inMemRaftStatePersister struct {
raftState RaftState
mu sync.Mutex
}
func newImMemRaftStatePersister() *inMemRaftStatePersister {
return &inMemRaftStatePersister{
raftState: RaftState{
Term: 0,
VotedFor: "",
Entries: make([]Entry, 0),
},
}
}
func (ps *inMemRaftStatePersister) SaveRaftState(state RaftState) error {
ps.mu.Lock()
defer ps.mu.Unlock()
ps.raftState = state
return nil
}
func (ps *inMemRaftStatePersister) LoadRaftState() (RaftState, error) {
ps.mu.Lock()
defer ps.mu.Unlock()
return ps.raftState, nil
}
// SnapshotPersister 接口的内存实现,开发测试用
type inMemSnapshotPersister struct {
snapshot Snapshot
mu sync.Mutex
}
func newInMemSnapshotPersister() *inMemSnapshotPersister {
return &inMemSnapshotPersister{}
}
func (ps *inMemSnapshotPersister) SaveSnapshot(snapshot Snapshot) error {
ps.mu.Lock()
defer ps.mu.Unlock()
ps.snapshot = snapshot
return nil
}
func (ps *inMemSnapshotPersister) LoadSnapshot() (Snapshot, error) {
ps.mu.Lock()
defer ps.mu.Unlock()
return ps.snapshot, nil
}