Git Product home page Git Product logo

go-redislock's Introduction

go-redislock

Go Release Action Report Coverage Doc License

English | 简体中文

Introduce

go-redislock is a library for Go that provides distributed lock functionality using Redis as the backend storage. Ensure data sharing and resource mutual exclusion under concurrent access in a distributed environment. Our distributed lock has the characteristics of reliability, high performance, timeout mechanism, reentrancy and flexible lock release method, which simplifies the use of distributed lock and allows you to focus on the realization of business logic.

Quick start

Install

go get -u github.com/jefferyjob/go-redislock

Use Demo

package main

import (
    "context"
    "fmt"
    "github.com/go-redis/redis/v8"
	redislock "github.com/jefferyjob/go-redislock"
)

func main() {
    // Create a Redis client
    redisClient := redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "",
        DB:       0,
    })

    // Create a context for canceling lock operations
    ctx := context.Background()

    // Create a RedisLock object
    lock := redislock.New(ctx, redisClient, "test_key")

    // acquire lock
    err := lock.Lock()
    if err != nil {
        fmt.Println("lock acquisition failed:", err)
        return
    }
    defer lock.UnLock() // unlock

    // Perform tasks during lockdown
    // ...

    fmt.Println("task execution completed")
}

Advanced usage

Custom Token

You can customize the lock's token functionality by using the WithToken option:

lock := redislock. New(ctx, redisClient,
    redislock. WithToken("your token")
)

Custom lock timeout

You can customize the lock's timeout function by using the WithTimeout option:

lock := redislock. New(ctx, redisClient,
    redislock.WithTimeout(time.Duration(10) * time.Second)
)

Automatic renewal

You can enable automatic renewal when acquiring a lock by using the WithAutoRenew option:

lock := redislock.New(ctx, redisClient,
	redislock.WithAutoRenew(true)
)

When using auto-renew, locks are automatically renewed periodically after acquisition to prevent locks from expiring. To manually renew a lock, the Renew method can be called.

Spin lock

A spinlock is a way to repeatedly acquire a lock until it becomes available. You can use the SpinLock method to implement a spinlock:

err := lock.SpinLock(time.Duration(5) * time.Second) // Try to acquire the lock, wait up to 5 seconds
if err != nil {
    fmt.Println("spinlock timeout:", err)
    return
}
defer lock.UnLock() // unlock

// Perform tasks during lockdown
// ...

Lock release

If you wish to release the lock manually without waiting for the lock to timeout, you can use the UnLock method:

err := lock.Lock()
if err != nil {
    fmt.Println("lock acquisition failed:", err)
    return
}

// perform tasks

err = lock.UnLock() // Release the lock manually
if err != nil {
    fmt.Println("lock release failed:", err)
    return
}

Precautions

  • Please make sure your Redis server is set up correctly, connected and running properly.
  • When using the automatic renewal function, ensure that there is no long-term blocking during task execution, so as not to cause the renewal to fail.
  • Consider using appropriate timeout settings to avoid deadlocks due to network issues etc.
  • Try to ensure that the same key is used to acquire and release locks to ensure correctness.
  • In the process of using locks, it is recommended to carefully design and test critical code blocks to avoid race conditions and deadlock problems.

License

This library is licensed under the MIT. See the LICENSE file for details.

go-redislock's People

Contributors

jefferyjob avatar dependabot[bot] avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.