etcd 分布式锁

1.安装etcd。如果是cluster至少要三个节点,在官网上下载二进制包解压,编写配置文件,如果使用阿里云或腾讯云等,记得安全组里面开放端口2379、2380。

name: 'node001'
data-dir: /data/etcd/cluster
listen-peer-urls: http://172.200.101.1:2380
listen-client-urls: http://172.200.101.1:2379,http://127.0.0.1:2379
initial-cluster-state: 'new'
initial-cluster-token: 'etcd-cluster-prod'
advertise-client-urls: http://172.200.101.1:2379
initial-advertise-peer-urls: http://172.200.101.1:2380
initial-cluster: node001=http://172.200.101.1:2380,node002=http://172.200.101.2:2380,node003=http://172.200.101.3:2380

name: 'node002'
data-dir: /data/etcd/cluster
listen-peer-urls: http://172.200.101.2:2380
listen-client-urls: http://172.200.101.2:2379,http://127.0.0.1:2379
initial-cluster-state: 'new'
initial-cluster-token: 'etcd-cluster-prod'
advertise-client-urls: http://172.200.101.2:2379
initial-advertise-peer-urls: http://172.200.101.2:2380
initial-cluster: node001=http://172.200.101.1:2380,node002=http://172.200.101.2:2380,node003=http://172.200.101.3:2380


name: 'node003'
data-dir: /data/etcd/cluster
listen-peer-urls: http://172.200.101.3:2380
listen-client-urls: http://172.200.101.3:2379,http://127.0.0.1:2379
initial-cluster-state: 'new'
initial-cluster-token: 'etcd-cluster-prod'
advertise-client-urls: http://172.200.101.3:2379
initial-advertise-peer-urls: http://172.200.101.3:2380
initial-cluster: node001=http://172.200.101.1:2380,node002=http://172.200.101.2:2380,node003=http://172.200.101.3:2380

 

2.启动。命令行 etcd --config-file xxx.conf

 

3.golang 客户端

import (
    "context"
    "time"

    "github.com/coreos/etcd/clientv3"
    "github.com/coreos/etcd/clientv3/concurrency"
    "github.com/pkg/errors"
)

type EtcdMutex struct {
    s *concurrency.Session
    m *concurrency.Mutex
}

func NewMutex(key string, client *clientv3.Client) (mutex *EtcdMutex, err error) {
    mutex = &EtcdMutex{}
    mutex.s, err = concurrency.NewSession(client)
    if err != nil {
        return
    }   
    mutex.m = concurrency.NewMutex(mutex.s, key)
    return
}

func (mutex *EtcdMutex) Lock() (err error) {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) //设置5s超时
    defer cancel()
    if err = mutex.m.Lock(ctx); err != nil {
        err = errors.Wrap(err, "获取分布式锁失败")
    }   
    return
}

func (mutex *EtcdMutex) Unlock() (err error) {
   err = mutex.m.Unlock(context.TODO())
    if err != nil {
     return
    } 
    err = mutex.s.Close()
    if err != nil {
     return
    } 
    return
}

 

 

 

posted @ 2018-10-29 14:40  yyanbiao  阅读(3057)  评论(0编辑  收藏  举报