当前位置:网站首页>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.")
}
边栏推荐
猜你喜欢

【故障诊断分析】基于matlab FFT轴承故障诊断(包络谱)【含Matlab源码 2002期】

根据一个字段的内容去更新另一个字段的数据,这样的sql语句该怎么样书写

以训辅教,以战促学 | 新版攻防世界平台正式上线运营!
![(Part of it is not understood, and the notes are not completed) [Graph Theory] Difference Constraints](/img/e0/385579fc8657db8b175318bd739908.gif)
(Part of it is not understood, and the notes are not completed) [Graph Theory] Difference Constraints

【图像隐藏】基于matlab混合DWT-HD-SVD数字图像水印方法技术【含Matlab源码 2007期】

optional

张驰咨询:企业实施精益管理的最大障碍,只把精益作为一种工具和方法

Clapper that can interact with the audience in real time

Leetcode Weekly 304

深度学习网络模型的改进与调整
随机推荐
Resolving C# non-static field, method or property "islandnum.Program.getIslandCount(int[][], int, int)" requires an object reference
CSRF-跨站请求伪造-相关知识
【请教】SQL语句按列1去重来计算列2之和
About the local server problem after ue4.27 pixel streaming package
【杂】pip换国内源教程及国内源地址
逆变器锁相原理及DSP实现
【故障诊断分析】基于matlab FFT轴承故障诊断(包络谱)【含Matlab源码 2002期】
C# FileInfo class
punch day05
实例030:回文数
July 18-July 31, 2022 (Ue4 video tutorials and documentation, 20 hours. Total 1412 hours, 8588 hours left)
【机器学习】实验3布置:贝叶斯垃圾邮件识别
自然语言处理 文本预处理(下)(张量表示、文本数据分析、文本特征处理等)
Swagger的简单介绍,集成,以及如何在生产环境中关闭swagger,在测试和开发环境中自动打开
【机器学习】课程设计布置:某闯关类手游用户流失预测
SimpleChannelInboundHandler使用总结
速看!PMP新考纲、PMBOK第七版解读
Pagoda+FastAdmin 404 Not Found
张驰咨询:企业实施精益管理的最大障碍,只把精益作为一种工具和方法
在VMware上安装Metasploitable2