当前位置:网站首页>Go implements distributed locks
Go implements distributed locks
2022-08-02 07:48:00 【rainy day on the sun】
点击链接查看我的个人博客,文章更全更详细
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.")
}
边栏推荐
猜你喜欢
实例028:递归求等差数列
Wuhan 2022 organizing of the high-performance computing added new ecological development of high-performance computing
Gradle系列——Gradle插件(基于Gradle文档7.5)day3-2
吃透Chisel语言.30.Chisel进阶之通信状态机(二)——FSMD:以Popcount为例
Facebook社媒营销的5大技巧,迅速提高独立站转化率!
论文《Deep Multifaceted Transformers for Multi-objective Ranking in Large-Scale E-commerce Recommender》
“蔚来杯“2022牛客暑期多校训练营5,签到题KBGHFCD
LeetCode 2312. 卖木头块
条件构造器~wapper
张驰课堂:六西格玛培训工具——箱线图
随机推荐
从云计算到函数计算
Neo4j 中文开发者月刊 - 202207期
PWA 踩坑 - 第一次加载页面后无法获取CacheStorage某些资源
【CV】OpenVINO安装教程
C#重点问题之Struct和Class的异同
正则表达式
FaceBook社媒营销高效转化技巧分享
【机器学习】实验2布置:基于回归分析的大学综合得分预测
实验7 MPLS实验
WebGPU 导入[2] - 核心概念与重要机制解读
[21天学习挑战赛——内核笔记](一)——设备树的概述(硬件、目标、效果、文件类型)
【ROS基础】rosbag 的使用方法
【CNN回归预测】基于matlab卷积神经网络CNN数据回归预测【含Matlab源码 2003期】
【网络】IP、子网掩码
Resolving C# non-static field, method or property "islandnum.Program.getIslandCount(int[][], int, int)" requires an object reference
The second day HCIP
MySQL-FlinkCDC-Hudi实时入湖
2022年数据泄露平均成本高达435万美元,创历史新高!
OC-NSString
Link with Game Glitch(spfa判负环)