gpt4 book ai didi

go - 如何使用 etcd 选举 api

转载 作者:IT王子 更新时间:2023-10-29 01:47:22 32 4
gpt4 key购买 nike

etcd v3 的新主要版本引入了新的并发原语。其中之一是选举

该 api 不支持开始事件并返回(其他)获胜者,这意味着我们需要查询领导者。这使得事情变得复杂,因为现在我们有两条并发路径,一条运行事件,另一条监控领导者变更。如果我们希望所有节点都运行领导者并回退到跟随者,那么同步这两者的最佳做法是什么。

    go func() {
if err := election.Campaign(this.ctx, this.Address); err != nil {
this.log.Error("election campaign failed", zap.Error(err))
}
}()

for {
select {
case response, ok := <-observations:
if !ok {
this.log.Warn("election observation channel closed")
return
}

value := string(response.Kvs[0].Value)
change := LeaderChanged{strings.EqualFold(value, this.Address), value}

select {
case changes <- change:
// should we figure out if we are a leader at this point?
case <-session.Done():
// it might be that we lost leadership
}
}
}

最佳答案

目前选举 API 不允许您简单地执行此操作。但是你可以在 goroutine 中运行选举代码并通过以下方式查询选举结果使用 election.Leader() 调用。

go func() {
if err := election.Campaign(this.ctx, this.Address); err != nil {
this.log.Error("election campaign failed", zap.Error(err))
}

fmt.Printf("we are leader")

for {
select {
case response, ok := <-observations:
if !ok {
this.log.Warn("election observation channel closed")
return
}

value := string(response.Kvs[0].Value)
change := LeaderChanged{strings.EqualFold(value, this.Address), value}

select {
case changes <- change:
// should we figure out if we are a leader at this point?
case <-session.Done():
// it might be that we lost leadership
}
}
}
}()

// Wait until we have a leader before continuing
for {
resp, err := election.Leader(this.ctx)
if err != nil {
if err != concurrency.ErrElectionNoLeader {
this.log.Warn("Leader returned error", err)
return
}
time.Sleep(time.Millisecond * 300)
continue
}
// Report if we are not leader
if string(resp.Kvs[0].Value) != this.Address {
fmt.Println("we are NOT leader")
}
break
}

带连接中断和初始化的领导者选举的完整例子领导汇报可见here .

关于go - 如何使用 etcd 选举 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45382331/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com