glock

package module
v1.1.11 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

README

Glock

all lock module and ratelimit using redis for controll.

Go Reference

install

go get github.com/teng231/glock

usage

many structs and methods, not all but i think it's help you for lock.

counter lock

Counter lock: It's distributed counter, counter can run up or run down. If run up, you can hanlder check and it's not atomic before all node. Counter down or coundown it's good. Helpful for count turn.

func Run(){
	cd, err := StartCountLock(&ConnectConfig{
		RedisAddr:"localhost:6379",
		RedisPw: "",
		Prefix: "test3_",
		Timelock: time.Minute,
		RedisDb: 1,
	})
	if err != nil {
		log.Print(err)
		t.Fail()
	}
	cd.Start("test1", 100, time.Minute)
	cur, _ := cd.DecrBy("test1", 1)
	log.Print(cur)
	if cur != 99 {
		log.Print(cur)
		t.Fail()
	}
}
distributed lock

As You know about this. It's can be lock for all node. Request run one by one, depend on a key. If 2 request going at the same time. Fist request come run and when its done. Second request continue process.

func Run(){
	dl, err := StartDistributedLock(&ConnectConfig{
		RedisAddr:"localhost:6379",
		RedisPw: "",
		Prefix: "test3_",
		Timelock: time.Minute,
		RedisDb: 1,
	})
	if err != nil {
		panic(err)
	}
    lctx, err := dl.Lock("test-redsync")
    if err := dl.Unlock(lctx); err != nil {
				panic(err)
	}
}

If many request coming. Distributed lock it not good because many ping request to check redis. Redis can be down then lock system down.

kmutex

It's local lock like distributed lock but using mutex and waitgroup. You can using it combine with distributed lock.

func Run(){
	km := CreateKmutexInstance()
	km.Lock("key")
	defer km.Unlock("key")
}
limiter

handler limit like counter lock. but have duration

func Run(){
    r, err := StartLimiter(&ConnectConfig{
		RedisAddr:"localhost:6379",
		RedisPw: "",
		Timelock: time.Minute,
		RedisDb: 1,
	})
	if err != nil {
		panic(err)
	}
	if err := r.Allow("key1", Second, 5); err != nil {
		log.Print(err)
	}
	if err := r.Allow("key1", Second, 5); err != nil {
		log.Print(err)
	}
	if err := r.Allow("key1", Second, 5); err != nil {
		log.Print(err)
	}
	if err := r.Allow("key1", Second, 5); err != nil {
		log.Print(err)
	}
	if err := r.Allow("key1", Second, 5); err != nil {
		log.Print(err)
	}
	if err := r.Allow("key1", Second, 5); err != nil {
		log.Print(err)
	}
	time.Sleep(1 * time.Second)
	if err := r.Allow("key1", Second, 5); err != nil {
		log.Print(err)
	}
}
optimistic lock

like distributed lock but request 2 come at the same time. It's will return false. Redis will lower traffics

func Run(){
    ol, err := StartOptimisticLock(&ConnectConfig{
		RedisAddr:"localhost:6379",
		RedisPw: "",
		Prefix: "test3_",
		Timelock: time.Minute,
		RedisDb: 1,
	}
	)
	if err != nil {
		panic(err)
	}
	if err := ol.Lock("key1"); err != nil {
		log.Print(err)
	}
}

Documentation

Index

Constants

View Source
const (
	StatusLocked         = "locked"
	StatusNotPersist     = "error_persist"
	StatusInvalidCounter = "invalid_counter"
	StatusCountdownDone  = "countdown_done"
	Empty                = "empty"
	CantParse            = "can't parse"
)
View Source
const (
	Second     = "second"
	Minute     = "minute"
	Hour       = "hour"
	Day        = "day"
	Week       = "week"
	Restricted = "restricted"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type ConnectConfig added in v1.1.1

type ConnectConfig struct {
	RedisAddr     string
	RedisPw       string
	RedisUsername string
	Prefix        string
	Timelock      time.Duration
	RedisDb       int
	// for distributed lock
	MaxRetries      int
	MinRetryBackoff time.Duration
	MaxRetryBackoff time.Duration
	PoolSize        int
	// add timezone
	Timezone string
}

type CountLock

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

func CreateCountLock

func CreateCountLock(redisAddr, redisPw, prefix string, timelock time.Duration) (*CountLock, error)

CreateCountLock deprecated

func StartCountLock added in v1.1.1

func StartCountLock(cf *ConnectConfig) (*CountLock, error)

StartCountLock

func (*CountLock) Current

func (cl *CountLock) Current(key interface{}) (int, error)

func (*CountLock) DecrBy

func (cl *CountLock) DecrBy(key interface{}, count int64) (int, error)

func (*CountLock) Existed added in v1.1.7

func (cl *CountLock) Existed(key interface{}) (bool, error)

func (*CountLock) IncrBy

func (cl *CountLock) IncrBy(key interface{}, count int64) (int, error)

func (*CountLock) Start

func (cl *CountLock) Start(key interface{}, startWith int, expired time.Duration) error

Start: khởi động 1 tiến trình bộ đếm. bắt đầu bằng startWith và thời hạn hiệu lực của bộ đếm là expired Start có thể dùng để reset counter về 1 giá trị nào đó.

func (*CountLock) StopCounter added in v1.1.3

func (cl *CountLock) StopCounter(key interface{}) error

type DistributedLock

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

func CreateDistributedLock

func CreateDistributedLock(addr, pw, prefix string, timelock time.Duration) (*DistributedLock, error)

CreateDistributedLock deprecated

func StartDistributedLock added in v1.1.1

func StartDistributedLock(cf *ConnectConfig) (*DistributedLock, error)

func (*DistributedLock) Lock

func (d *DistributedLock) Lock(key string) (*LockContext, error)

func (*DistributedLock) Unlock

func (d *DistributedLock) Unlock(lc *LockContext) error

type DistributedQueue

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

func ConnectDistributedQueue

func ConnectDistributedQueue(client *redis.Client, prefix string, timelock time.Duration) (*DistributedQueue, error)

func (*DistributedQueue) List

func (q *DistributedQueue) List(key string, start, stop int64, f func([]string) error) error

List start with page 0

func (*DistributedQueue) Pop

func (q *DistributedQueue) Pop(key string, out interface{}) error

func (*DistributedQueue) Push

func (q *DistributedQueue) Push(key string, values ...interface{}) error

func (*DistributedQueue) Set

func (q *DistributedQueue) Set(key string, values ...interface{}) error

func (*DistributedQueue) Shift

func (q *DistributedQueue) Shift(key string, out interface{}) error

func (*DistributedQueue) Size

func (q *DistributedQueue) Size(key string) (int64, error)

func (*DistributedQueue) Unshift

func (q *DistributedQueue) Unshift(key string, values ...interface{}) error

type ICountLock

type ICountLock interface {
	// Start is config start
	Start(key interface{}, startWith int, expired time.Duration) error
	// DecrBy decrease count
	DecrBy(key interface{}, count int64) (int, error)
	// Current get current count
	Current(key interface{}) (int, error)
	// Existed check key existed
	Existed(key interface{}) (bool, error)
	// IncrBy increase count
	IncrBy(key interface{}, count int64) (int, error)
	// IncrBy stop counter
	StopCounter(key interface{}) error
}

type IDistributedLock

type IDistributedLock interface {
	// Lock is close request in. Lock all request come to the gate
	Lock(key string) (*LockContext, error)
	// Unlock release the gate
	Unlock(lc *LockContext) error
}

type IDistributedQueue

type IDistributedQueue interface {
	// Push to the left
	Unshift(key string, values ...interface{}) error
	// Push to the right
	Push(key string, values ...interface{}) error
	// release 1 item right
	Pop(key string, out interface{}) error
	// release 1 item right
	Shift(key string, out interface{}) error
	// List item in list
	List(key string, start, stop int64, f func([]string) error) error
	// Size get current size of list
	Size(key string) (int64, error)
}

type IKmutex

type IKmutex interface {
	Lock(key interface{})
	Unlock(key interface{})
}

type ILimiter

type ILimiter interface {
	// Allow is access comming request and increase counter
	Allow(key string, per string, count int) error
	// Immediate reset counter
	Reset(key string) error
	// Allow using with duration = day
	// AllowInDay(key string, count int) error
	AllowInWeek(key string, count int) error
}

Copyright (c) 2017 Pavel Pravosud https://github.com/rwz/redis-gcra/blob/master/vendor/perform_gcra_ratelimit.lua

type IOptimisticLock

type IOptimisticLock interface {
	Lock(key string, otherDuration ...time.Duration) error
	Unlock(key string) error
}

type Kmutex

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

Kmutex Can be locked by unique ID

func CreateKmutexInstance

func CreateKmutexInstance() *Kmutex

CreateKmutexInstance new Kmutex

func WithLock

func WithLock(l sync.Locker) *Kmutex

WithLock Create new Kmutex with user provided lock

func (*Kmutex) Lock

func (km *Kmutex) Lock(key interface{})

Lock Kmutex by unique ID

func (Kmutex) Locker

func (km Kmutex) Locker(key interface{}) sync.Locker

Locker Return a object which implement sync.Locker interface A Locker represents an object that can be locked and unlocked.

func (*Kmutex) Unlock

func (km *Kmutex) Unlock(key interface{})

Unlock Kmutex by unique ID

type Limiter

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

func CreateLimiter

func CreateLimiter(addr, pw string, timelock time.Duration) (*Limiter, error)

CreateLimiter deprecated

func StartLimiter added in v1.1.1

func StartLimiter(cf *ConnectConfig) (*Limiter, error)

func (*Limiter) Allow

func (r *Limiter) Allow(key string, per string, count int) error

func (*Limiter) AllowInWeek added in v1.1.4

func (r *Limiter) AllowInWeek(key string, count int) error

func (*Limiter) Reset

func (r *Limiter) Reset(key string) error

type LockContext

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

type OptimisticLock

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

func CreateOptimisticLock

func CreateOptimisticLock(addr, pw, prefix string, timelock time.Duration) (*OptimisticLock, error)

CreateOptimisticLock deprecated

func StartOptimisticLock added in v1.1.1

func StartOptimisticLock(cf *ConnectConfig) (*OptimisticLock, error)

func (*OptimisticLock) Lock

func (ol *OptimisticLock) Lock(key string, otherDuration ...time.Duration) error

func (*OptimisticLock) Unlock

func (ol *OptimisticLock) Unlock(key string) error

Jump to

Keyboard shortcuts

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