Skip to content

⚡A collection of redis tools, including distributed lock, cas, casEx, cad

License

Notifications You must be signed in to change notification settings

zehuamama/redis-tools

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

redis-tools

Go Report Card GitHub top language GitHub CodeFactor go_version

redis-tools is a collection of redis tools, including distributed lock, cas, casEx, cad .

Quick Start

Fisrt, create a demo and import the redis-tools and redis client :

> go mod init demo

> go get github.com/zehuamama/redis-tools
> go get github.com/go-redis/redis/v8

Distributed lock

The trylock case :

package main

import (
	"context"
	"log"

	"github.com/go-redis/redis/v8"
	tools "github.com/zehuamama/redis-tools"
)

func main() {
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	disLock, err := tools.NewRedisLock(client, "lock resource")
	if err != nil {
		log.Fatal(err)
	}

	succ, err := disLock.TryLock(context.Background())
	if err != nil {
		log.Println(err)
        return
	}

	if succ {
		defer disLock.Unlock(context.Background())
	}
}

and spinlock case :

    succ, err := disLock.SpinLock(context.Background(), 5)  // retry 5 times
	if err != nil {
		log.Println(err)
        return
	}

	if succ {
		defer disLock.Unlock(context.Background())
	}

Redis Tools

compare and swap case :

func main() {
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	succ, err := tools.NewTools(client).Cas(context.Background(), "cas_key", "old value", "new value")
	if err != nil {
		log.Println(err)
		return
	}

    ...
}

and compare and delete case :

    succ, err := tools.NewTools(client).Cad(context.Background(), "cas_key", "old value")
	if err != nil {
		log.Println(err)
		return
	}

Contributing

If you are intersted in contributing to redis-tools, please see here: CONTRIBUTING

License

redis-tools is licensed under the term of the BSD 2-Clause License

About

⚡A collection of redis tools, including distributed lock, cas, casEx, cad

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages