redislock

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2023 License: MIT Imports: 7 Imported by: 0

README

redislock

Redis context-based locker with auto refresh.

Examples

package main

import (
	"context"
	"time"

	"github.com/khasanovbi/redislock"
	"github.com/redis/go-redis/v9"
)

func doJobUnderLockWithContext(ctx context.Context) {
}

func main() {
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})

	// Lock will automatically update the TTL time every RefreshPeriod.
	// The configuration can be set either for the entire Locker or for each Lock request individually.
	locker, err := redislock.New(rdb, redislock.WithRefreshPeriod(time.Minute), redislock.WithTTL(10*time.Minute))
	if err != nil {
		panic(err)
	}

	// Try to get lock.
	lock, ctx, err := locker.Lock(context.Background(), "my_lock_key")
	if err != nil {
		panic(err)
	}

	defer func() {
		_ = lock.Unlock()
	}()
	
	doJobUnderLockWithContext(ctx)
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrAlreadyLocked = errors.New("already locked")
	ErrUnlocked      = errors.New("explicitly unlocked")
)

Functions

This section is empty.

Types

type Lock

type Lock struct {
	// contains filtered or unexported fields
}

func (*Lock) Unlock

func (m *Lock) Unlock() error

type Locker

type Locker struct {
	// contains filtered or unexported fields
}

func New

func New(client redis.UniversalClient, options ...Option) (*Locker, error)

func (*Locker) Lock

func (m *Locker) Lock(ctx context.Context, key string, options ...Option) (*Lock, context.Context, error)
Example
package main

import (
	"context"
	"time"

	"github.com/khasanovbi/redislock"
	"github.com/redis/go-redis/v9"
)

func doJobUnderLockWithContext(ctx context.Context) { //nolint:revive
}

func main() {
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})

	locker, err := redislock.New(rdb, redislock.WithRefreshPeriod(time.Minute), redislock.WithTTL(10*time.Minute))
	if err != nil {
		panic(err)
	}

	lock, ctx, err := locker.Lock(context.Background(), "my_lock_key")
	if err != nil {
		panic(err)
	}

	defer func() {
		_ = lock.Unlock()
	}()

	doJobUnderLockWithContext(ctx)
}

type Option

type Option func(m *config)

func WithRefreshPeriod

func WithRefreshPeriod(refreshPeriod time.Duration) Option

func WithTTL

func WithTTL(ttl time.Duration) Option

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL