Open anonymity12 opened 2 months ago
ref:https://www.cnblogs.com/JulianHuang/p/16166069.html
kimi给出的方案:
package main import ( "context" "fmt" "log" "time" clientv3 "go.etcd.io/etcd/client/v3" "go.etcd.io/etcd/client/v3/concurrency" ) func main() { log.Printf("start eletion process\n") // 假设有三个节点的Etcd集群 endpoints := []string{"gpfs01-node164:2379", "gpfs02-node165:2379", "gpfs03-node166:2379"} // 初始化Etcd客户端 cli, err := clientv3.New(clientv3.Config{ Endpoints: endpoints, DialTimeout: 5 * time.Second, }) if err != nil { log.Fatalf("Error creating etcd client: %v", err) } defer cli.Close() // 创建会话 s,_ := concurrency.NewSession(cli) defer s.Close() // 创建选举器 election := concurrency.NewElection(s, "/my-election-prefix") // 竞选领导者 id := fmt.Sprintf("node-%d", 5) // 假设当前节点ID为node-5:166 if err := election.Campaign(context.TODO(), id); err != nil { log.Fatalf("Error campaigning for election: %v", err) } log.Printf("Node %s is the leader\n", id) // 领导者执行的任务 leaderTask := func(id string) { for { select { case <-s.Done(): log.Printf("Node %s lost leadership\n", id) return case <-time.After(1 * time.Second): log.Printf("Node %s is performing leader tasks\n", id) } } } // 运行领导者任务 go leaderTask(id) // 等待用户输入以放弃领导地位 fmt.Println("Press Enter to resign leadership...") var input string fmt.Scanln(&input) // 放弃领导地位 if err := election.Resign(context.TODO()); err != nil { log.Fatalf("Error resigning from election: %v", err) } log.Printf("Node %s resigned from leadership\n", id) }
你在不同的节点上,需要改动的是: id := fmt.Sprintf("node-%d", 5) // 假设当前节点ID为node-5:166 这一行
id := fmt.Sprintf("node-%d", 5) // 假设当前节点ID为node-5:166
结果就是 ,你输入回车,则是 让一个leader 退休。 其他从节点 则 不相应 回车; 静静等待 主节点 回车 死亡后 ,按照启动顺序,从节点 变味老大
ref:https://www.cnblogs.com/JulianHuang/p/16166069.html
kimi给出的方案: