当前位置:网站首页>Go 实现分布式锁
Go 实现分布式锁
2022-08-02 06:50:00 【太阳上的雨天】
点击链接查看我的个人博客,文章更全更详细
1. 基于redis 的 setnx
package main
import (
"fmt"
"sync"
"time"
"github.com/go-redis/redis"
)
func incr() {
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379",
Password: "root",
DB: 0,
})
var lockKey = "counter_lock"
var counterKey = "counter"
resp := client.SetNX(lockKey, 1, time.Second*5)
ok, err := resp.Result()
if err != nil || !ok {
fmt.Println(err, "lock result: ", ok)
return
}
getResp := client.Get(counterKey)
cntValue, err := getResp.Int64()
if err == nil || err == redis.Nil {
cntValue++
resp := client.Set(counterKey, cntValue, 0)
_, err := resp.Result()
if err != nil {
println("set value error!")
}
}
println("current counter is ", cntValue)
delResp := client.Del(lockKey)
unlockSuccess, err := delResp.Result()
if err == nil && unlockSuccess > 0 {
println("unlock success!")
} else {
println("unlock failed", err)
}
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
incr()
}()
}
wg.Wait()
}
2. 基于ZooKeeper
package main
import (
"time"
"github.com/samuel/go-zookeeper/zk"
)
func main() {
c, _, err := zk.Connect([]string{
"127.0.0.1"}, time.Second)
if err != nil {
panic(err)
}
l := zk.NewLock(c, "/lock", zk.WorldACL(zk.PermAll))
err = l.Lock()
if err != nil {
panic(err)
}
println("lock succ, do your business login")
time.Sleep(time.Second * 5)
l.Unlock()
println("unlock succ, finish business logic")
}
3. 基于etcd
package main
import (
"log"
"github.com/zieckey/etcdsync"
)
func main() {
m, err := etcdsync.New("/mylock", 10, []string{
"http://127.0.0.1:2379"})
if m == nil || err != nil {
panic(err)
}
err = m.Lock()
if err != nil {
log.Printf("etcdsync.lock failed")
} else {
log.Printf("etcd sync.lock succ")
}
log.Printf("get the lock, do something here.")
err = m.Unlock()
if err != nil {
log.Printf("etcdsync.unlock failed")
} else {
log.Printf("etcdsync unlock succ")
}
log.Printf("unlock the lock, do something here.")
}
边栏推荐
猜你喜欢

交换--STP协议

Vscode connect to remote server "Acquiring the lock on the/home / ~ 'problem

CAT1 4G+Ethernet development board Tencent cloud mobile phone WeChat applet display temperature and delivery control

速看!PMP新考纲、PMBOK第七版解读

数据库概论-MySQL的数据表的基本操作

Redis 常用命令和基本数据结构(数据类型)

实例026:递归求阶乘

实例032:反向输出II
![(Notes are not completed) [Graph Theory] Traversal of graphs](/img/1d/d2909dcfa0ab5c207005971a7b4a2d.gif)
(Notes are not completed) [Graph Theory] Traversal of graphs

(部分不懂,笔记整理未完成)【图论】差分约束
随机推荐
解决C#非静态字段、方法或属性“islandnum.Program.getIslandCount(int[][], int, int)”要求对象引用
逆变器绝缘检测检测功能及软件实现
Resolving C# non-static field, method or property "islandnum.Program.getIslandCount(int[][], int, int)" requires an object reference
sql 远程访问链接服务器
2022年数据泄露平均成本高达435万美元,创历史新高!
Neo4j 中文开发者月刊 - 202207期
自然语言处理 文本预处理(下)(张量表示、文本数据分析、文本特征处理等)
【机器学习】实验4布置:AAAI会议论文聚类分析
Two good php debug tutorials
【心电信号】基于matlab心率检测【含Matlab源码 1993期】
实例026:递归求阶乘
August 2022 plan, focusing on ue4 video tutorials
实例031:字母识词
【云原生】如何快速部署Kubernetes
反射课后习题及做题记录
[Dataset][VOC] Eyewear dataset 6000 in VOC format
张驰课堂:六西格玛测量系统的误差分析与判定
MySQL-FlinkCDC-Hudi实时入湖
2020美亚团队赛复盘
chrome plugin development guide