https://github.com/itcomusic/redismutex
Distributed locking implementation using Redis
https://github.com/itcomusic/redismutex
distributed go golang lock mutex redis rwlock
Last synced: 3 months ago
JSON representation
Distributed locking implementation using Redis
- Host: GitHub
- URL: https://github.com/itcomusic/redismutex
- Owner: itcomusic
- License: mit
- Created: 2023-01-06T12:27:47.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-02-23T17:55:07.000Z (over 2 years ago)
- Last Synced: 2024-06-20T05:14:09.010Z (12 months ago)
- Topics: distributed, go, golang, lock, mutex, redis, rwlock
- Language: Go
- Homepage:
- Size: 18.6 KB
- Stars: 2
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# RWMutex
[![build-img]][build-url]
[![pkg-img]][pkg-url]
[![coverage-img]][coverage-url]Distributed rw locking implementation using [Redis](https://redis.io/docs/manual/patterns/distributed-locks/) with auto extended lock expiration.
RWMutex can work in write prefer mode, when readers do not acquire lock if writer has declared intention to lock.## Example
```go
package mainimport (
"context"
"fmt"
"log"
"github.com/redis/redis/v9"
"github.com/itcomusic/redismutex"
)func main() {
// connect to redis
rc := redis.NewClient(&redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
})
defer rc.Close()// init mutex
mx := redismutex.NewMutex(rc, "mutex_name")// lock, optionally add key and lock_key will be "mutex_name:key"
lock, ok := mx.Lock(redismutex.WithKey("key")) // also available RLock, TryLock, TryRLock
if !ok {
log.Fatalln("could not obtain lock, disconnected from redis?")
}
defer lock.Unlock()// lock implements interface context.Context
handler := func(ctx context.Context) {
select {
case <-ctx.Done():
fmt.Println("lock expired")
default:
fmt.Println("lock active")
}
}fmt.Printf("lock %q! \n", lock.Key())
handler(lock)
}
```## License
[MIT License](LICENSE)[build-img]: https://github.com/itcomusic/redismutex/workflows/test/badge.svg
[build-url]: https://github.com/itcomusic/redismutex/actions
[pkg-img]: https://pkg.go.dev/badge/github.com/itcomusic/redismutex.svg
[pkg-url]: https://pkg.go.dev/github.com/itcomusic/redismutex
[coverage-img]: https://codecov.io/gh/itcomusic/redismutex/branch/main/graph/badge.svg
[coverage-url]: https://codecov.io/gh/itcomusic/redismutex