https://github.com/kei2100/locker
An interface and implementations of named lock for exclusivity control between processes and threads.
https://github.com/kei2100/locker
go golang lock mysql postgresql
Last synced: 4 months ago
JSON representation
An interface and implementations of named lock for exclusivity control between processes and threads.
- Host: GitHub
- URL: https://github.com/kei2100/locker
- Owner: kei2100
- License: apache-2.0
- Created: 2022-05-08T06:03:01.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2022-06-05T13:10:54.000Z (about 4 years ago)
- Last Synced: 2024-06-21T03:16:53.937Z (about 2 years ago)
- Topics: go, golang, lock, mysql, postgresql
- Language: Go
- Homepage:
- Size: 36.1 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
locker
=======
## Description
locker provides an interface and implementations of named lock for exclusivity control between processes and threads.
```go
func ExampleLocker() {
// setup *sql.DB
db := setupPostgres()
defer db.Close()
// Acquire the lock by specified key. (Using PostgreSQL pg_advisory_lock)
key := randHex(16)
locker := postgres.NewLocker(db)
lock, err := locker.Get(context.Background(), key)
if err != nil {
panic(fmt.Sprintf("failed to acquire: %+v", err))
}
// Releases the lock at the end of the function
defer lock.Release()
fmt.Println("lock acquired")
// The same key will be blocked until the lock is released
done := make(chan interface{})
go func() {
defer close(done)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
lock, err := locker.Get(ctx, key)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return
}
panic(fmt.Sprintf("unexpected err: %+v", err))
}
lock.Release()
fmt.Println("unexpected lock acquired")
}()
<-done
// Output:
// lock acquired
}
```
## Lock implementations
Currently provides following implementations.
* postgres.Locker
* postgres.Locker provides a simple lock mechanism using PostgreSQL [pg_advisory_lock](https://www.postgresql.org/docs/14/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS)
* Recommend that using the [pgx](https://github.com/jackc/pgx) PostgreSQL Driver
* mysql.Locker
* mysql.Locker provides a simple lock mechanism using MySQL [GET_LOCK](https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html#function_get-lock)
## Installation
```bash
$ go get github.com/kei2100/locker
```