Etcd
2020-07-15 本文已影响0人
会理发的店小二
Etcd
leader选举
package main
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/clientv3/concurrency"
"log"
"time"
)
const prefix = "/election-demo"
const prop = "local"
var leaderFlag bool
func main() {
endpoints := []string{"192.168.6.137:2379"}
donec := make(chan struct{})
cli, err := clientv3.New(clientv3.Config{Endpoints: endpoints})
if err != nil {
log.Fatal(err)
}
defer cli.Close()
go campaign(cli, prefix, prop)
go func() {
ticker := time.NewTicker(time.Duration(5) * time.Second)
for {
select {
case <-ticker.C:
doCrontab()
}
}
}()
<-donec
}
func campaign(c *clientv3.Client, election string, prop string) {
for {
s, err := concurrency.NewSession(c, concurrency.WithTTL(15))
if err != nil {
fmt.Println(err)
continue
}
e := concurrency.NewElection(s, election)
ctx := context.TODO()
if err = e.Campaign(ctx, prop); err != nil {
fmt.Println(err)
continue
}
fmt.Println("elect: success")
leaderFlag = true
select {
case <-s.Done():
leaderFlag = false
fmt.Println("elect: expired")
}
}
}
func doCrontab() {
if leaderFlag == true {
fmt.Println("doCrontab")
}
}
解决依赖问题
- 问题
go get go.etcd.io/etcd/clientv3时出错
# github.com/coreos/etcd/clientv3/balancer/resolver/endpoint
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/resolver/endpoint/endpoint.go:114:78: undefined: resolver.BuildOption
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/resolver/endpoint/endpoint.go:182:31: undefined: resolver.ResolveNowOption
# github.com/coreos/etcd/clientv3/balancer/picker
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/picker/err.go:37:44: undefined: balancer.PickOptions
../../pkg/mod/github.com/coreos/etcd@v3.3.18+incompatible/clientv3/balancer/picker/roundrobin_balanced.go:55:54: undefined: balancer.PickOptions
- 解决
go mod edit -require=google.golang.org/grpc@v1.26.0