golang使用redis分布式锁_can be used to set the clock drift factor.-程序员宅基地

技术标签: redigo  golang  Redis  go-redis  redsync  redis分布式锁  

由于时间流逝,代码库更新,现在下面的代码已经不适用了,我写了一遍文章更新了代码

传送门 golang使用redis分布式锁 [2020年更新]

昨天由于项目需求,需要使用redis分布式锁,在网上找了半天,也没有找到一个简单的教程,经过自己研究,了解简单使用方法,都可以直接拿过来自己用,下面我就发出来给大家分享一下。

  1.  首先下载 github.com/garyburd/redigo,因为这个分布式锁是根据上面所实现;
  2. 下载  gopkg.in/redsync.v1 这个就是实现分布式锁的源代码(如果测试需要下载 github.com/stvp/tempredis);
  3. 我在Windows上不能运行,因为不支持,在Liunx上完美运行,其他的就没有试过了;
  4. 我们先来看下源码
package redsync

import (
	"crypto/rand"
	"encoding/base64"
	"sync"
	"time"

	"github.com/garyburd/redigo/redis"
)

// A Mutex is a distributed mutual exclusion lock.
type Mutex struct {
	name   string
	expiry time.Duration

	tries int
	delay time.Duration

	factor float64

	quorum int

	value string
	until time.Time

	nodem sync.Mutex

	pools []Pool
}

 

name   string          //命名一个名字
expiry time.Duration   //最多可以获取锁的时间,超过自动解锁
tries int              //失败最多获取锁的次数
delay time.Duration    //获取锁失败后等待多少时间后重试
factor float64
quorum int
value string           //每一个锁独有一个值,
until time.Time
nodem sync.Mutex
pools []Pool           //连接池 

// New creates and returns a new Redsync instance from given Redis connection pools.
func New(pools []Pool) *Redsync {
	return &Redsync{
		pools: pools,
	}
}

// NewMutex returns a new distributed mutex with given name.
func (r *Redsync) NewMutex(name string, options ...Option) *Mutex {
	m := &Mutex{
		name:   name,
		expiry: 8 * time.Second,
		tries:  32,
		delay:  500 * time.Millisecond,
		factor: 0.01,
		quorum: len(r.pools)/2 + 1,
		pools:  r.pools,
	}
	for _, o := range options {
		o.Apply(m)
	}
	return m
}

// An Option configures a mutex.
type Option interface {
	Apply(*Mutex)
}

// OptionFunc is a function that configures a mutex.
type OptionFunc func(*Mutex)

// Apply calls f(mutex)
func (f OptionFunc) Apply(mutex *Mutex) {
	f(mutex)
}

// SetExpiry can be used to set the expiry of a mutex to the given value.
func SetExpiry(expiry time.Duration) Option {
	return OptionFunc(func(m *Mutex) {
		m.expiry = expiry
	})
}

// SetTries can be used to set the number of times lock acquire is attempted.
func SetTries(tries int) Option {
	return OptionFunc(func(m *Mutex) {
		m.tries = tries
	})
}

// SetRetryDelay can be used to set the amount of time to wait between retries.
func SetRetryDelay(delay time.Duration) Option {
	return OptionFunc(func(m *Mutex) {
		m.delay = delay
	})
}

// SetDriftFactor can be used to set the clock drift factor.
func SetDriftFactor(factor float64) Option {
	return OptionFunc(func(m *Mutex) {
		m.factor = factor
	})
}

这里的SET*方法,是自定义设置Mutex的参数

下面就分享出自己写的测试代码

package main

import (
	"gopkg.in/redsync.v1"
	"testing"
	"github.com/garyburd/redigo/redis"
	"time"
	"fmt"
)

//redis命令执行函数
func DoRedisCmdByConn(conn *redis.Pool,commandName string, args ...interface{}) (interface{}, error) {
	redisConn := conn.Get()
	defer redisConn.Close()
	//检查与redis的连接
	return redisConn.Do(commandName, args...)
}


func TestRedis(t *testing.T) {

	//单个锁
	//pool := newPool()
	//rs := redsync.New([]redsync.Pool{pool})
	//mutex1 := rs.NewMutex("test-redsync1")
	//
	//mutex1.Lock()
	//conn := pool.Get()
	//conn.Do("SET","name1","ywb1")
	//conn.Close()
	//mutex1.Unlock()
	curtime := time.Now().UnixNano()
	//多个同时访问
	pool := newPool()
	mutexes := newTestMutexes([]redsync.Pool{pool}, "test-mutex", 2)
	orderCh := make(chan int)
	for i,v :=range mutexes {
		go func(i int,mutex *redsync.Mutex) {
			if err := mutex.Lock(); err != nil {
				t.Fatalf("Expected err == nil, got %q", err)
				return
			}
			fmt.Println(i,"add lock ....")
			conn := pool.Get()
            DoRedisCmdByConn(pool,"SET",fmt.Sprintf("name%v",i),fmt.Sprintf("name%v",i))
			str,_ := redis.String(DoRedisCmdByConn(pool,"GET",fmt.Sprintf("name%v",i))
			fmt.Println(str)
            DoRedisCmdByConn(pool,"DEL",fmt.Sprintf("name%v",i))
			conn.Close()
			mutex.Unlock()
			fmt.Println(i,"del lock ....")
			orderCh <- i
		}(i,v)
	}
	for range mutexes {
		<-orderCh
	}
	fmt.Println(time.Now().UnixNano() - curtime )
}

func newTestMutexes(pools []redsync.Pool, name string, n int) []*redsync.Mutex {
	mutexes := []*redsync.Mutex{}
	for i := 0; i < n; i++ {
		mutexes = append(mutexes,redsync.New(pools).NewMutex(name,
			redsync.SetExpiry(time.Duration(2)*time.Second),
			redsync.SetRetryDelay(time.Duration(10)*time.Millisecond)),
		)
	}
	return mutexes
}

func newPool() *redis.Pool {
	return &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: time.Duration(24) * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", "127.0.0.1:6379")
			if err != nil {
				panic(err.Error())
				//s.Log.Errorf("redis", "load redis redisServer err, %s", err.Error())
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			if err != nil {
				//s.Log.Errorf("redis", "ping redis redisServer err, %s", err.Error())
				return err
			}
			return err
		},
	}
}

这就是代码实现,可以自己封装,也可以拿去直接用。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/billgates_wanbin/article/details/82769666

智能推荐

【matlab】【函数学习记录】寻找矩阵最大和次大极值点_matlab如何求一个矩阵最大值和次大值-程序员宅基地

文章浏览阅读1.7k次。【matlab】【函数学习记录】寻找矩阵最大和次大极值点。_matlab如何求一个矩阵最大值和次大值

如何利用PowerShell完成的Windows服务器系统安全加固实践和基线检测_利用shell检查linux安全基线-程序员宅基地

文章浏览阅读4.7k次,点赞2次,收藏5次。0x00 前言简述最近单位在做等保测评,由本人从事安全运维方面的工作(PS:曾经做过等保等方面的安全服务),所以自然而然的与信安的测评人员一起对接相关业务系统的检查,在做主机系统测评检查时发现了系统中某些配置不符合等保要求,需要对不满足要求的主机做进一步整改,好在我们众多的系统基本都是运行在虚拟机上搭建的kubernetes集群中,这样一来就可以尽可能减少加固系统给应用带来的影响,我们可以一台一台加固更新。在这样环境的驱动下不得不将通宵熬夜,我准备好了枸杞和保温杯,当然也把测试环境也准备了一套,并将以前_利用shell检查linux安全基线

颜色空间,图像格式,彩色转灰度函数-程序员宅基地

文章浏览阅读835次。、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、rgb颜色空间灰度图像是一个特殊的彩色图像,r=g=b,如图所以,要将彩色图像转化为灰度图像,只需令每个像素的r=g=b=x即可.而x等于多少,视不同情况而定。补充:黑色 r=0 g=0 b=0白色 r=..._9a:e8:ec:54:a4:oc

centos启动卡死进不去界面,停留在started GNOME display manager_centos7 started gnome display manager-程序员宅基地

文章浏览阅读1.4w次,点赞7次,收藏9次。重装centos7时,遇到见面卡死在[ok] started GNOME display manager此时按ctrl + alt f3 切换到登录界面,输入用户名 , 密码即可登录_centos7 started gnome display manager

微信小程序学习笔记-(10)-猫眼电影案例_微信小程序猫眼电影-程序员宅基地

文章浏览阅读7.9k次,点赞5次,收藏57次。使用前需要在微信公众号平台配置HTTPS服务器域名,但是可以做一个不合验的操作来发起请求.配置服务器域名的文档:https://mp.weixin.qq.com/wxamp/devprofile/get_profile?token=290458817&lang=zh_CN一,wx.reqiuest的常用参数二,创建项目的初始化第一步:删除index和logs这两个没用的页面第二步:创建自己想要的页面和顶部的配置第三步:实现点击标签滑动效果三,API接口的使用1,通过wx.g_微信小程序猫眼电影

2022年团体程序设计天梯赛-模拟赛_天梯赛python洛希极限-程序员宅基地

文章浏览阅读6.4k次,点赞18次,收藏53次。前面几个题比较简单,不加题解了,后面几个题目附上文字题解。…实际上后面几个题解也写的比较简单,懒了…ps: 代码大部分是比赛的时候写的,有几个题目写的比较搓,大佬见谅。L1-1 自动编程 (5 分)输出语句是每个程序员首先要掌握的语句。Python 的输出语句很简单,只要写一个 print(X) 即可,其中 X 是需要输出的内容。本题就请你写一个自动编程机,对任何一个要输出的整数 N,给出输出这个整数的 Python 语句。输入格式:输入给出一个不超过 105 的正整数。输出格式:在一_天梯赛python洛希极限

随便推点

Google Earth Engine(GEE)——python检测 Sentinel-1 图像中的变化(part1)万字长文_sentinel-1 change detection-程序员宅基地

文章浏览阅读710次。在本教程中,我们将分析合成孔径雷达 (SAR) 图像,以检测地球表面具有统计意义的变化。正如副词“统计地”暗示的那样,我们需要对 SAR 图像的统计特性有基本的了解才能继续,而形容词“显着”意味着我们学习了假设检验的基础知识。我们将特别关注 GEE 档案中双极化强度 Sentinel-1 SAR 图像的时间序列。教程分为四部分:1. 单视和多视图像统计 2. 假设检验 3.多时态变化检测 4. 应用大部分材料基于我的文本Image Analysis, Classification and Cha_sentinel-1 change detection

npm 报错 ERR! [email protected] serve vue-cli-service serve-程序员宅基地

文章浏览阅读706次。解决问题启动Vue项目执行npm run serve报错原因:使用了不同的编辑器,而且配置文件弄混了1.删除node_modules文件夹。2.使用国内镜像重新安装npm install --registry=https://registry.npm.taobao.orgnpm install -g cnpm --registry=https://registry.npm.taobao.orgcnpm install3.重新运行npm run serve...

AQS、ReentrantLock、ReentrantReadWriteLock 结构与源码分析_readwrite lock aqs-程序员宅基地

文章浏览阅读911次。AQS 以及其实现类 ReentrantLock、ReentrantReadWriteLock 源码分析。_readwrite lock aqs

伪代码基本规范_伪代码规范-程序员宅基地

文章浏览阅读2.9k次。插入排序的伪代码for j=2 to A.length key=A[j] //Insert A[j]into the sorted sequence A[1..j-1] i=j-1 while i&gt;0 and A[j]&gt;key A[i+1]=A[i] i=i-1 A[i+1}=key缩进表示块结构,比..._伪代码规范

How google test software_how goole test software-程序员宅基地

文章浏览阅读858次。好久没有写新文章了。今天转一下google的测试文章How google test software书的链接:http://www.amazon.com/Google-Tests-Software-James-Whittaker/dp/0321803027/ref=sr_1_1?ie=UTF8&qid=1323756294&sr=8-1当然也可以翻墙到下面的地址:http:_how goole test software

.repo/repo/main.py“, line 79 file=sys.stderr) SyntaxError: invalid syntax_file=sys.stderr) ^ syntaxerror: invalid syntax-程序员宅基地

文章浏览阅读7.4k次。.repo/repo/main.py", line 79 file=sys.stderr) SyntaxError: invalid syntax_file=sys.stderr) ^ syntaxerror: invalid syntax