redis 分布式锁

rddlock

github.com/everfore/rddlock

redis distribute lock

redis 分布式锁, 实现原理:redis分布式锁

Usage

Lock & UnLock

lockkey := "lock-key"
timeout_ms := 3000

locked, ex := rddlock.Lock(rds, lockkey, timeout_ms)
defer reelock.UnLock(rds, lockkey, ex)

LockRetry

retry_times := 10
locked, ex := reelock.LockRetry(rds, lockkey, timeout_ms, retry_times) // get lock by retry
defer reelock.UnLock(rds, lockkey, ex)

UnLockUnsafe

直接删除key,可能会有问题:若删除之前,该key已经超时且被其他进程获得锁,将会删除其他进程的锁;删除之后,锁被释放,进而会有其他进程2获得锁。。。雪崩

locked, _ := rddlock.Lock(rds, lockkey, timeout_ms)
defer reelock.UnLockUnsafe(rds, lockkey)

SyncDo 异步执行任务

err := SyncDo(rds, lockkey, timeout_ms, func(timeout chan bool) chan bool {
        ret := make(chan bool, 1)
        go func() {
            fmt.Println("doing...")
            // TODO SOMETHING
            select {
            case <-timeout:
                // do the rollback
                break
            case ret <- true:
                fmt.Println("success end.")
            }
        }()
        return ret
    })

test

success:200, avg:1.1074123 ms
failed:0, avg:NaN ms
--- PASS: TestLockTime (10.59s)

#local-redis
=== RUN   TestLockRetryTime
success:200, avg:1.1741205 ms
failed:0, avg:NaN ms
--- PASS: TestLockRetryTime (10.58s)

#uat-redis
=== RUN   TestLockRetryTime
success:200, avg:12.572702 ms
failed:0, avg:NaN ms
--- PASS: TestLockRetryTime (10.59s)

欢迎指正 github.com/everfore/rddlock

0 个评论

要回复文章请先登录注册