golang使用redis分布式锁

时间:2025-05-13 07:40:16

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

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

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

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

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

	"/garyburd/redigo/redis"
)

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

	tries int
	delay 

	factor float64

	quorum int

	value string
	until 

	nodem 

	pools []Pool
}

 

name   string          //命名一个名字
expiry    //最多可以获取锁的时间,超过自动解锁
tries int              //失败最多获取锁的次数
delay     //获取锁失败后等待多少时间后重试
factor float64
quorum int
value string           //每一个锁独有一个值,
until 
nodem 
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 * ,
		tries:  32,
		delay:  500 * ,
		factor: 0.01,
		quorum: len()/2 + 1,
		pools:  ,
	}
	for _, o := range options {
		(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 ) Option {
	return OptionFunc(func(m *Mutex) {
		 = 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) {
		 = tries
	})
}

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

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

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

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

package main

import (
	"/redsync.v1"
	"testing"
	"/garyburd/redigo/redis"
	"time"
	"fmt"
)

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


func TestRedis(t *) {

	//单个锁
	//pool := newPool()
	//rs := ([]{pool})
	//mutex1 := ("test-redsync1")
	//
	//()
	//conn := ()
	//("SET","name1","ywb1")
	//()
	//()
	curtime := ().UnixNano()
	//多个同时访问
	pool := newPool()
	mutexes := newTestMutexes([]{pool}, "test-mutex", 2)
	orderCh := make(chan int)
	for i,v :=range mutexes {
		go func(i int,mutex *) {
			if err := (); err != nil {
				("Expected err == nil, got %q", err)
				return
			}
			(i,"add lock ....")
			conn := ()
            DoRedisCmdByConn(pool,"SET",("name%v",i),("name%v",i))
			str,_ := (DoRedisCmdByConn(pool,"GET",("name%v",i))
			(str)
            DoRedisCmdByConn(pool,"DEL",("name%v",i))
			()
			()
			(i,"del lock ....")
			orderCh <- i
		}(i,v)
	}
	for range mutexes {
		<-orderCh
	}
	(().UnixNano() - curtime )
}

func newTestMutexes(pools [], name string, n int) []* {
	mutexes := []*{}
	for i := 0; i < n; i++ {
		mutexes = append(mutexes,(pools).NewMutex(name,
			((2)*),
			((10)*)),
		)
	}
	return mutexes
}

func newPool() * {
	return &{
		MaxIdle:     3,
		IdleTimeout: (24) * ,
		Dial: func() (, error) {
			c, err := ("tcp", "127.0.0.1:6379")
			if err != nil {
				panic(())
				//("redis", "load redis redisServer err, %s", ())
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c , t ) error {
			_, err := ("PING")
			if err != nil {
				//("redis", "ping redis redisServer err, %s", ())
				return err
			}
			return err
		},
	}
}

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