go实现redis分布式锁

4 篇文章 0 订阅

下载 github.com/garyburd/redigo,这个分布式锁是根据上面所实现;
下载 gopkg.in/redsync.v1 这个就是实现分布式锁的源代码(如果测试需要下载 github.com/stvp/tempredis);

看下源码

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
		},
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 Redis 分布式锁的基本思路是利用 Redis 的 SETNX 命令(SET if Not eXists)实现。SETNX 命令会在 key 不存在的情况下,将 key 的值设为 value,如果 key 已经存在,则不做任何操作。 以下是一个简单的 Golang 实现 Redis 分布式锁的代码示例: ```go package redislock import ( "fmt" "time" "github.com/go-redis/redis/v7" ) type RedisLock struct { redisClient *redis.Client key string value string expiration time.Duration } func NewRedisLock(redisClient *redis.Client, key, value string, expiration time.Duration) *RedisLock { return &RedisLock{ redisClient: redisClient, key: key, value: value, expiration: expiration, } } func (r *RedisLock) Lock() (bool, error) { success, err := r.redisClient.SetNX(r.key, r.value, r.expiration).Result() if err != nil { return false, err } return success, nil } func (r *RedisLock) Unlock() error { err := r.redisClient.Del(r.key).Err() if err != nil { return err } return nil } ``` 在上面的代码中,NewRedisLock 函数用于创建一个 RedisLock 实例,需要传入 Redis 客户端、锁的 key、锁的值、锁的过期时间。Lock 方法用于尝试获取锁,如果获取成功,返回 true,否则返回 false。Unlock 方法用于释放锁。 以下是一个简单的使用示例: ```go package main import ( "fmt" "time" "github.com/go-redis/redis/v7" "github.com/yourusername/redislock" ) func main() { redisClient := redis.NewClient(&redis.Options{ Addr: "localhost:6379", DB: 0, }) lock := redislock.NewRedisLock(redisClient, "my-lock", "my-value", 10*time.Second) success, err := lock.Lock() if err != nil { fmt.Println("failed to acquire lock:", err) return } if !success { fmt.Println("lock is already held by another process") return } defer lock.Unlock() // Do some work } ``` 在上面的示例中,我们创建了一个 Redis 客户端,并且创建了一个 RedisLock 实例。然后,我们调用 Lock 方法尝试获取锁,如果获取成功,就可以进行一些需要加锁的操作。最后,我们调用 Unlock 方法释放锁。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值