Etcd

作者: 会理发的店小二 | 来源:发表于2020-07-15 23:48 被阅读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

相关文章

网友评论

      本文标题:Etcd

      本文链接:https://www.haomeiwen.com/subject/ucwshktx.html