Skip to content

Redlock: a redis based distributed lock implementation in golang

License

Notifications You must be signed in to change notification settings

amyangfei/redlock-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

52 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RedLock-go

Go Report Card Build Status Coverage Status

Redis distributed locks in Golang

This Golang lib implements the Redis-based distributed lock manager algorithm described in this blog post.

Installation

This library requires a Go version with modules support. So make sure to initialize a Go module:

go mod init github.com/<user>/<repo>

And then install this library via go get

go get github.com/amyangfei/redlock-go/v3

Usage

To create a lock manager:

lockMgr, err := redlock.NewRedLock(
    ctx,
    []string{
        "tcp://127.0.0.1:6379",
        "tcp://127.0.0.1:6380",
        "tcp://127.0.0.1:6381",
})

To acquire a lock:

import "github.com/amyangfei/redlock-go/v3/redlock"

ctx := context.Background()
expirity, err := lockMgr.Lock(ctx, "resource_name", 200*time.Milliseconds)

Where the resource name is an unique identifier of what you are trying to lock and 200ms the validity time for lock.

The err is not nil if the lock was not acquired (you may try again), otherwise an expirity(which is a time.Duration) larger than zero is returned representing the remaining time that lock will be valid.

To release a lock:

import "github.com/amyangfei/redlock-go/v3/redlock"

ctx := context.Background()
err := lockMgr.UnLock(ctx, "resource_name")

You can find sample code in _examples dir.

Options

A KV cache is used for local lock item query, currently this library provides two KV cache implemenations: map based cache and freecache based cache. Besides some cache related options can be set by passing an option map.

map based cache

import "github.com/amyangfei/redlock-go/v3/redlock"

lock, err := redlock.NewRedLock(
    ctx,
    []string{
        "tcp://127.0.0.1:6379",
        "tcp://127.0.0.1:6380",
        "tcp://127.0.0.1:6381",
    },
    redlock.WithCacheType(redlock.CacheTypeSimple),
    redlock.WithCacheDisableGC(false),
    redlock.WithGCInterval(time.Minute),
)

freecache based cache

import "github.com/amyangfei/redlock-go/v3/redlock"

lock, err := redlock.NewRedLock(
    ctx,
    []string{
        "tcp://127.0.0.1:6379",
        "tcp://127.0.0.1:6380",
        "tcp://127.0.0.1:6381",
    },
    redlock.WithCacheType(redlock.CacheTypeFreeCache),
    redlock.WithCacheSize(10*1024*1024), // 10 Megabytes
)

About

Redlock: a redis based distributed lock implementation in golang

Resources

License

Stars

Watchers

Forks

Packages

No packages published