当前位置:网站首页>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协议
- SQL server 2014 怎么一次性导出多个查询结果?
- At age 94, pioneer Turing award winner, computational complexity theory, Juris Hartmanis, died
- 【CV】OpenVINO安装教程
- 结构体大小计算--结构体内存对齐
- 【ROS基础】rosbag 的使用方法
- SimpleChannelInboundHandler使用总结
- [Dataset][VOC] Male and female dataset voc format 6188 sheets
- 【暑期每日一题】洛谷 P3156 【深基15.例1】询问学号
- Summer Summary (3)
猜你喜欢
聊天机器人如何提升独立站的营销水平?
电商库存系统的防超卖和高并发扣减方案
yml字符串读取时转成数字了怎么解决
(2022牛客多校五)C-Bit Transmission(思维)
交换网络----三种生成树协议
解决:- SPY: No data found for this date range, symbol may be delisted报错
See the picture to understand | How to choose sales indicators to measure the health of business growth
【故障诊断分析】基于matlab FFT轴承故障诊断(包络谱)【含Matlab源码 2002期】
HCIP day one
海缆探测仪TSS350(二)
随机推荐
How does abaqus quickly import the assembly of other cae files?
【杂】pip换国内源教程及国内源地址
暑假第五周总结
typescript 'props' is declared but its value is never read solution
【ROS基础】map、odom、base_link、laser 的理解 及其 tf 树的理解
张驰课堂:六西格玛测量系统的误差分析与判定
【论文精读】Geometric Structure Preserving Warp for Natural Image Stitching
实例027:递归输出
[21天学习挑战赛——内核笔记](一)——设备树的概述(硬件、目标、效果、文件类型)
optional
Clapper that can interact with the audience in real time
逆变器锁相原理及DSP实现
使用hutool做本地缓存的工具类
2022夏暑假每日一题(六)
笔记本开机黑屏提示:ERROR 0199:System Security-Security password retry count exceeded
实例030:回文数
数据库概论-MySQL的数据表的基本操作
【暑期每日一题】洛谷 P3156 【深基15.例1】询问学号
有趣的网站
Analysis of GCC compiler technology