nlock
A simple but powerful distributed lock
Get Started
Download
go get github.com/inuggets/nlock
Usage
Redis lock
import lock "github.com/inuggets/nlock"
redisPool := lock.NewRedisPool("localhost:6379", "PASSWORD")
key := "test"
l := lock.NewRedisLock(redisPool, 15) // ttl is 15s
if l.Lock(key) {
defer l.Unlock(key)
if l.HasLock(key) { // You can check if has lock
...
}
// Do something
...
}
Lock with waiting time
l := lock.NewRedisLock(redisPool, 15) // ttl is 15s
if lock.LockWait(key, 3) { // Wait up to 3s if key is locked but others
defer l.Unlock(key)
}
Methods
- Lock(key string) bool // lock
- LockWait(key string, seconds int64) bool // lock with waiting time
- Locked(key string) bool // check if locked
- HasLock(key string) bool // check if has/own lock
- Unlock(key string) bool // unlock
MySQL lock
import lock "github.com/inuggets/nlock"
db, _ := lock.NewMysqlClient("localhost:3306", "DB", "USER", "PASSWORD")
l := lock.NewMysqlLock(db, 15)
key := "test"
l := lock.NewRedisLock(redisPool, 15) // ttl is 15s
if l.Lock(key) {
defer l.Unlock(key)
}
License
nlock is under the MIT license. See the LICENSE for detail.