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
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM