枯木逢春不在茂
年少且惜镜边人
写在前面
lab2B已经完成的raft的大部分内容,2C主要是对currentterm,[]log,voteFor 进行持久化存储,后边3B也会修改这一部分的代码,还有就是2B中提到的心跳被拒后回退机制太慢,需要优化。
具体实现
首先是持久化函数,lab中给出的代码可以直接套用
// save Raft's persistent state to stable storage,
// where it can later be retrieved after a crash and restart.
// see paper's Figure 2 for a description of what should be persistent.
//
func (rf *Raft) persist() {
// Your code here (2C).
// 不用加锁,外层逻辑会锁
w := new(bytes.Buffer)
e := labgob.NewEncoder(w)
e.Encode(rf.currentTerm)
e.Encode(rf.votedFor)
e.Encode(rf.log)
data := w.Bytes()
DPrintf("RaftNode[%d] persist starts, currentTerm[%d] voteFor[%d] log[%v]", rf.me, rf.currentTerm, rf.votedFor, rf.log)
rf.persister.SaveRaftState(data)
}
//
// restore previously persisted state.
//
func (rf *Raft) readPersist(data []byte) {
if data == nil || len(data) < 1 {
// bootstrap without any state?
return
}
// Your code here (2C).
r := bytes.NewBuffer(data)
d := labgob.NewDecoder(r)
rf.mu.Lock()
defer rf.mu.Unlock()
d.Decode(&rf.currentTerm)
d.Decode(&rf.votedFor)
d.Decode(&rf.log)
}
type AppendEntriesArgs struct {
Term int
LeaderId int
PrevLogIndex int
PrevLogTerm int
Entries []LogEntry
LeaderCommit int
}
type AppendEntriesReply struct {
Term int
Success bool
ConflictIndex int
ConflictTerm int
}
也就是增加了ConflictIndex和ConflictTerm这两个字段
func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) {
rf.mu.Lock()
defer rf.mu.Unlock()
DPrintf("RaftNode[%d] Handle AppendEntries, LeaderId[%d] Term[%d] CurrentTerm[%d] role=[%s] logIndex[%d] prevLogIndex[%d] prevLogTerm[%d] commitIndex[%d] Entries[%v]",
rf.me, rf.leaderId, args.Term, rf.currentTerm, rf.role, len(rf.log), args.PrevLogIndex, args.PrevLogTerm, rf.commitIndex, args.Entries)
reply.Term = rf.currentTerm
reply.Success = false
reply.ConflictIndex = -1
reply.ConflictTerm = - 1
defer func() {
DPrintf("RaftNode[%d] Return AppendEntries, LeaderId[%d] Term[

这篇博客详细介绍了 Raft 分布式一致性算法中关于日志持久化、心跳应答冲突处理及日志同步的优化。优化主要包括在 follower 回复中增加 ConflictIndex 和 ConflictTerm 字段,以及在 leader 处理心跳应答时如何更智能地回退 nextIndex。当 follower 的 log 缺失或 term 不匹配时,leader 能更精确地确定同步起始点,减少无效同步,提高系统效率。
最低0.47元/天 解锁文章
1495

被折叠的 条评论
为什么被折叠?



