distlock

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2021 License: MIT Imports: 6 Imported by: 0

README

distlock

Go codecov Go Reference

Distributed Locks implementation in Go
backed on
Redis, MySQL, PostgreSQL, etc.

Features

  1. Namespace (names in the same namespace are unique, default namespace is "default")
  2. Auto/No expiration (auto-released after a specific time or never expire)
  3. Support multiple backends:
    • Redis
    • MySQL
    • PostgreSQL

Usage

import (
    "github.com/ggicci/distlock"
    "github.com/gomodule/redigo/redis"
)

var redisPool = &redis.Pool{
    // ... configure your redis client
}

var heavyRequestsGuard = distlock.New(
    distlock.NewRedisProvider(redisPool),
    distlock.WithNamespace("heavy_requests"),
    distlock.WithLockLifetime(10 * time.Second), // lifetime: 10s
)

user := session.CurrentUser()
mu := heavyRequestsGuard.New(
    user.Username,
    WithLockLifetime(time.Minute), // override the default lifetime option: 10s
)
if err := mu.Lock(); err != nil {
    return err
}
defer mu.Unlock()

// do sth.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAlreadyLocked = errors.New("already locked")
	ErrNotLocked     = errors.New("not locked")
)

Functions

This section is empty.

Types

type Mutex

type Mutex interface {
	Lock() error
	Unlock() error
	String() string
}

type MutexFactory

type MutexFactory interface {
	New(id string, opts ...Option) Mutex
}

func New

func New(provider Provider, defaultOpts ...Option) MutexFactory

type NamedLock

type NamedLock interface {
	GetId() string
	GetOwner() string
	GetLifetime() time.Duration
}

type Option

type Option interface {
	Apply(*mutex)
}

Option is an option for tweaking Mutex.

func WithLockLifetime

func WithLockLifetime(lifetime time.Duration) Option

WithLockLifetime returns an option that configures Mutex.lifetime.

func WithNamespace

func WithNamespace(ns string) Option

WithNamespace returns an option that configures Mutex.ns.

type Provider

type Provider interface {
	Name() string
	Lock(info NamedLock) error
	Unlock(info NamedLock) error
}

func NewMySQLProvider

func NewMySQLProvider(db *sql.DB, tableName string) (Provider, error)

func NewPostgreSQLProvider

func NewPostgreSQLProvider(db *sql.DB, tableName string) (Provider, error)

func NewRedisProvider

func NewRedisProvider(redisPool RedisPool) (Provider, error)

type RedisPool

type RedisPool interface {
	// Get returns a connection from the pool.
	Get() redis.Conn
}

RedisPool represents a pool of redis connections.

Jump to

Keyboard shortcuts

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