6.824 Lab 2: Key/Value Server
在本实验中,需要构建一个键/值服务器, 以确保每个操作在网络故障 的情况下都只执行一次, 并且操作是线性化的。
网络故障
示例代码
Go
type Clerk struct {
server *labrpc.ClientEnd
workerId int64
seq int64
}
Go
func (ck *Clerk) PutAppend(key string, value string, op string) string {
reply := new(PutAppendReply)
for !reply.Ok {
ck.server.Call("KVServer."+op, &PutAppendArgs{key, value, ck.workerId, ck.seq}, reply)
}
ck.seq++
v := reply.Value
reply.Ok = false
return v
}
Go
type KVServer struct {
mu sync.RWMutex
m map[string]string
seqSet map[string]string
}
Go
func (kv *KVServer) Append(args *PutAppendArgs, reply *PutAppendReply) {
kv.mu.Lock()
defer kv.mu.Unlock()
key := strconv.Itoa(int(args.WorkerId)) + strconv.Itoa(int(args.Seq))
//检查是不是执行过
if v, ok := kv.seqSet[key]; ok {
reply.Ok = true
reply.Value = v
return
}
//删除上一次的缓存
delete(kv.seqSet, strconv.Itoa(int(args.WorkerId))+strconv.Itoa(int(args.Seq-1)))
//执行Append
s := kv.m[args.Key]
kv.seqSet[key] = s
kv.m[args.Key] = s + args.Value
reply.Value = s
reply.Ok = true
}
tips
- 测试文件运行在linux下比windows快不少,建议在linux测试