Etcd

会理发的店小二 · · 689 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

689 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传