@@ -70,16 +70,19 @@ func (e *Election) Campaign(ctx context.Context, val string) error {
7070 s := e .session
7171 client := e .session .Client ()
7272
73+ // 如果 session 没有指定 lease id,则会为每个 session 生成新的 lease id
74+ // key 的格式为 prefix+leaseID
7375 k := fmt .Sprintf ("%s%x" , e .keyPrefix , s .Lease ())
76+ // 当 key 不存在时,createRevision 是 0
7477 txn := client .Txn (ctx ).If (v3 .Compare (v3 .CreateRevision (k ), "=" , 0 ))
75- txn = txn .Then (v3 .OpPut (k , val , v3 .WithLease (s .Lease ())))
78+ txn = txn .Then (v3 .OpPut (k , val , v3 .WithLease (s .Lease ()))) // 为 key attach 租约
7679 txn = txn .Else (v3 .OpGet (k ))
7780 resp , err := txn .Commit ()
7881 if err != nil {
7982 return err
8083 }
8184 e .leaderKey , e .leaderRev , e .leaderSession = k , resp .Header .Revision , s
82- if ! resp .Succeeded {
85+ if ! resp .Succeeded { // 如果 key 已经存在了
8386 kv := resp .Responses [0 ].GetResponseRange ().Kvs [0 ]
8487 e .leaderRev = kv .CreateRevision
8588 if string (kv .Value ) != val {
@@ -107,6 +110,7 @@ func (e *Election) Campaign(ctx context.Context, val string) error {
107110}
108111
109112// Proclaim lets the leader announce a new value without another election.
113+ // leader 宣布新的值,即修改 leaderKey 对应的 value。如果提交失败则清空 leaderKey
110114func (e * Election ) Proclaim (ctx context.Context , val string ) error {
111115 if e .leaderSession == nil {
112116 return ErrElectionNotLeader
@@ -134,6 +138,7 @@ func (e *Election) Resign(ctx context.Context) (err error) {
134138 return nil
135139 }
136140 client := e .session .Client ()
141+ // 将 leaderkey, leaderRev 从数据库中删除,从而发起新的选举
137142 cmp := v3 .Compare (v3 .CreateRevision (e .leaderKey ), "=" , e .leaderRev )
138143 resp , err := client .Txn (ctx ).If (cmp ).Then (v3 .OpDelete (e .leaderKey )).Commit ()
139144 if err == nil {
0 commit comments