xsync

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 6 Imported by: 0

README

分布式锁

基于Redis实现分布式锁

推荐阅读

  • https://segmentfault.com/a/1190000038988087
  • http://kaito-kidd.com/2021/06/08/is-redis-distributed-lock-really-safe/
使用说明
  1. 锁必须设置过期时间,默认是1s,可以根据接口的超时时间设置
  2. 常见的并发都是用户维度的,例如在两个平台发起同样的请求,因此锁的key一般需要与uid绑定
  3. 对于Redis宕机导致锁丢失带来的不可控影响没有保证(如果redis可以提供高可用服务,基本可以忽略此情况)
使用方式
import "github.com/SigmaGavin/slardar/pkg/xsync"


// 经典场景,每日签到,一个用户只能签一次,签到会送积分和发券和累计
name := "default"                                                    // 使用默认的redis集群
key := fmt.Sprintf("test_%d_%s", uid, time.Now.Format("20060102"))   // 分布式锁的key格式

async := xsync.New(name, key)
// async.SetExp(锁超时时间,单位为秒,默认1s)

err = async.Run(ctx, func(ctx context.Context) error {
    // 1. 送积分 
    err := db.AddIntegration(ctx, uid, 10)
    if err != nil {
        return	
    }
    
    // 2. 发券
    err := db.AddCoupon(ctx, uid, 1)
    if err != nil {
        return
    }
    
    // 3. 累计签到
    err := db.AddCheck(ctx, uid)
    
    // 4. 其他业务逻辑
})


if IsMissingLockErr(err) {
    // 说明并发时未获得锁
    fmt.Println("系统繁忙,请重试~~~雅蠛蝶~~~")
    return
}

if err != nil {
    // 出现的其他错误
	return
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMissingLock = errors.Errorf("missing lock")

ErrMissingLock 未获得锁

Functions

func IsMissingLockErr

func IsMissingLockErr(err error) bool

判断是否是未获得锁的错误

Types

type Async

type Async struct {
	// contains filtered or unexported fields
}

Async 分布式锁

func New

func New(name string, key string) *Async

New 构建一个 Asyc 对象 默认超时时间1s 默认不重试

func (Async) Run

func (async Async) Run(ctx context.Context, cb func(ctx context.Context) error) (err error)

Run 运行

func (*Async) SetExp

func (async *Async) SetExp(exp time.Duration) error

SetExp 设置超时时间(秒) exp 默认为1 exp >= 1

func (*Async) SetRetry

func (async *Async) SetRetry(cnt int32, interval time.Duration) error

SetRetry 设置同一个协程中未获得锁的情况下的重试次数,及等待间隔 默认不重试 次数cnt 和 间隔interval 必须>=0 原则上非特殊情况不鼓励重试

type Item

type Item int64

Item 锁的内容

func Lock

func Lock(ctx context.Context, name string, key string, exp int32) (Item, error)

Lock 业务上锁 name: 指定的redis集群 exp: 单位是秒

func (Item) HasLock

func (item Item) HasLock() bool

HasLock 是否有获得锁

func (Item) Unlock

func (item Item) Unlock(ctx context.Context, name string, key string) (isSuccess bool, err error)

Unlock 业务解锁 name: 指定的redis集群

Jump to

Keyboard shortcuts

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