当前位置:网站首页>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.")
}
边栏推荐
- About the local server problem after ue4.27 pixel streaming package
- 【暑期每日一题】洛谷 P1192 台阶问题
- SimpleChannelInboundHandler使用总结
- docker 安装mysql
- The nacos source code can not find the istio package
- Submit code process
- C# FileInfo class
- 数据库概论-MySQL的数据表的基本操作
- 分离轴定理SAT凸多边形精确碰撞检测
- 【图像隐藏】基于matlab混合DWT-HD-SVD数字图像水印方法技术【含Matlab源码 2007期】
猜你喜欢
随机推荐
2020美亚团队赛复盘
自然语言处理 文本预处理(上)(分词、词性标注、命名实体识别等)
July 18-July 31, 2022 (Ue4 video tutorials and documentation, 20 hours. Total 1412 hours, 8588 hours left)
张驰课堂:六西格玛培训工具——箱线图
入门opencv,欢笑快乐每一天
(Notes are not completed) [Graph Theory] Traversal of graphs
See the picture to understand | How to choose sales indicators to measure the health of business growth
Unity Shader学习(七)纹理图像的简单使用
JS初识高阶函数和函数柯里化
【机器学习】课程设计布置:某闯关类手游用户流失预测
【杂】pip换国内源教程及国内源地址
Redis 常用命令和基本数据结构(数据类型)
有趣的网站
jvm 二之 栈帧内部结构
图腾柱和推挽电路介绍
At age 94, pioneer Turing award winner, computational complexity theory, Juris Hartmanis, died
交换--STP协议
PWA 踩坑 - 第一次加载页面后无法获取CacheStorage某些资源
PMP新考纲考试内容介绍
(Part of it is not understood, and the notes are not completed) [Graph Theory] Difference Constraints









