You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Simplified distributed locking implementation using Redis.
For more information, please see examples.
Examples
import (
"context""fmt""log""time""github.com/bsm/redislock""github.com/redis/go-redis/v9"
)
funcmain() {
// Connect to redis.client:=redis.NewClient(&redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
})
deferclient.Close()
// Create a new lock client.locker:=redislock.New(client)
ctx:=context.Background()
// Try to obtain lock.lock, err:=locker.Obtain(ctx, "my-key", 100*time.Millisecond, nil)
iferr==redislock.ErrNotObtained {
fmt.Println("Could not obtain lock!")
// It default 0 times backoff retrive, next step should be return or continue in a loop.return
} elseiferr!=nil {
log.Fatalln(err)
}
// Don't forget to defer Release.deferlock.Release(ctx)
fmt.Println("I have a lock!")
// Sleep and check the remaining TTL.time.Sleep(50*time.Millisecond)
ifttl, err:=lock.TTL(ctx); err!=nil {
log.Fatalln(err)
} elseifttl>0 {
fmt.Println("Yay, I still have my lock!")
}
// Extend my lock.iferr:=lock.Refresh(ctx, 100*time.Millisecond, nil); err!=nil {
log.Fatalln(err)
}
// Sleep a little longer, then check.time.Sleep(100*time.Millisecond)
ifttl, err:=lock.TTL(ctx); err!=nil {
log.Fatalln(err)
} elseifttl==0 {
fmt.Println("Now, my lock has expired!")
}
}