当前位置:网站首页>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.")
}
边栏推荐
- SQL执行顺序
- Revitalize rural circular economy and digital chain to link agricultural "ecological chain"
- FaceBook社媒营销高效转化技巧分享
- 【论文精读】Geometric Structure Preserving Warp for Natural Image Stitching
- 吃透Chisel语言.31.Chisel进阶之通信状态机(三)——Ready-Valid接口:定义、时序和Chisel中的实现
- 【图像去噪】基于matlab双立方插值和稀疏表示图像去噪【含Matlab源码 2009期】
- 每周推荐短视频:为什么产品开发需要数字化?如何做到数字化?
- Vscode连接远程服务器出现‘Acquiring lock on/home/~’问题
- Analysis of GCC compiler technology
- 第06章 索引的数据结构【2.索引及调优篇】【MySQL高级】
猜你喜欢

【图像去噪】基于matlab双立方插值和稀疏表示图像去噪【含Matlab源码 2009期】

(2022牛客多校五)D-Birds in the tree(树形DP)

Xilinx约束学习笔记—— 时序约束

【心电信号】基于matlab心率检测【含Matlab源码 1993期】

optional

typescript 'props' is declared but its value is never read solution

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

新产品立大功 伟世通第二季度营收双增

逆变器绝缘检测检测功能及软件实现

PWA 踩坑 - 第一次加载页面后无法获取CacheStorage某些资源
随机推荐
System.Security.SecurityException: 未找到源,但未能搜索某些或全部事件日志。不可 访问的日志: Security
The second day HCIP
倍福使用AdsRemote组件实现和C#的ADS通讯
【暑期每日一题】洛谷 P1255 数楼梯
论文《Deep Multifaceted Transformers for Multi-objective Ranking in Large-Scale E-commerce Recommender》
入门opencv,欢笑快乐每一天
[21天学习挑战赛——内核笔记](一)——设备树的概述(硬件、目标、效果、文件类型)
【暑期每日一题】洛谷 P1192 台阶问题
张驰课堂:六西格玛培训工具——箱线图
【杂】pip换国内源教程及国内源地址
Day 4 of HCIP
封装class类一次性解决全屏问题
C#重点问题之Struct和Class的异同
【机器学习】课程设计布置:某闯关类手游用户流失预测
【暑期每日一题】洛谷 P1551 亲戚
海缆探测仪TSS350(二)
逆变器锁相原理及DSP实现
typescript 'props' is declared but its value is never read solution
你认同这个观点吗?大多数企业的数字化都只是为了缓解焦虑
The nacos source code can not find the istio package