mutex

package module
v0.0.0-...-9f993a6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2020 License: GPL-3.0 Imports: 6 Imported by: 0

README

redis-mutex

基于redis的分布式锁。

锁的默认存活时间为5秒,上锁默认超时时间为3秒。支持上锁后自动刷新锁的存活时间,默认没有开启,可使用mutex.AutoRefresh方法开启。

使用demo:

    import mutex "github.com/yuanzhangcai/redis-mutex"

    // 初始化分布式锁
    err := mutex.Init(mutex.RedisServer("127.0.0.1:6379"), mutex.Password("12345678"), mutex.Prefix("lock_demo"))
	if err != nil {
		fmt.Println(1, err)
		return
	}

    // 创建分布式锁,
    // 可以通过:mutex.TTL、mutex.Timeout、mutex.AutoRefresh、mutex.Context方法修改默认参数
    m := mutex.NewMutex("Lock_key")

    // 上锁
	err = m.Lock()
	if err != nil {
		fmt.Println(err) // 上锁失败
		return
	}

    // do something

    m.Unlock() // 解锁

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrLockFailed 上锁失败
	ErrLockFailed = errors.New("lock failed")
	// ErrUnlockInvalid 无效解锁
	ErrUnlockInvalid = errors.New("unlock invalid")
	// ErrRefreshTTLFailed 刷新锁的存活时间失败
	ErrRefreshTTLFailed = errors.New("refresh ttl failed")
)

Functions

func Init

func Init(opt ...InitOption) error

Init 初始化分布式锁

Types

type InitOption

type InitOption func(*InitOptions)

InitOption 设置初始化分布锁参数参数

func Password

func Password(password string) InitOption

Password 设置redis密码

func Prefix

func Prefix(prefix string) InitOption

Prefix 设置redis前缀

func RedisServer

func RedisServer(server string) InitOption

RedisServer 设置redis地址

type InitOptions

type InitOptions struct {
	Prefix      string // redis键值前缀
	RedisServer string // redis服务器信息
	Password    string // redis密码
}

InitOptions 分布式锁参数

type Locker

type Locker interface {
	Lock() error
	RefreshTTL() error
	Unlock() error
	TTL() (time.Duration, error)
}

Locker 分布式锁接口

func NewMutex

func NewMutex(key string, opt ...Option) Locker

NewMutex 创建分布式锁

type Option

type Option func(*Options)

Option 设置分布锁参数

func AutoRefresh

func AutoRefresh(autoRefresh bool) Option

AutoRefresh 设置分布式锁过期时间是否自动刷新

func Context

func Context(ctx context.Context) Option

Context 设置上下文

func TTL

func TTL(ttl time.Duration) Option

TTL 设置分布式的存活时间

func Timeout

func Timeout(timeout time.Duration) Option

Timeout 设置分布式的存活时间

type Options

type Options struct {
	TTL            time.Duration // 锁的存活时间
	Timeout        time.Duration // 上锁超时时间
	AutoRefreshTTL bool          // 是否自动刷新锁的存活时间
	Retry          RetryStrategy // 重试策略
	Ctx            context.Context
}

Options 分布式锁参数

type RetryStrategy

type RetryStrategy interface {
	// After 返回重试时间,当前时之后多长时间重试
	After() time.Duration
}

RetryStrategy 重试策略

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL