Skip to content

Simplified distributed locking implementation using Redis

License

Notifications You must be signed in to change notification settings

creker/redislock-radix

 
 

Repository files navigation

redislock

Build Status GoDoc Go Report Card License

This is a fork of https://github.com/bsm/redislock that replaces go-redis with radix.

Simplified distributed locking implementation using Redis. For more information, please see examples.

Examples

import (
  "fmt"
  "time"

  "github.com/creker/redislock-radix"
  "github.com/mediocregopher/radix/v3"
)

func main() {
	// Connect to redis.
	client, err := radix.NewPool("tcp", "127.0.0.1:6379", 10)
	if err != nil {
		log.Fatalln(err)
	}
	defer client.Close()

	// Create a new lock client.
	locker := redislock.New(client)

	// Try to obtain lock.
	lock, err := locker.Obtain("my-key", 100*time.Millisecond, nil)
	if err == redislock.ErrNotObtained {
		fmt.Println("Could not obtain lock!")
	} else if err != nil {
		log.Fatalln(err)
	}

	// Don't forget to defer Release.
	defer lock.Release()
	fmt.Println("I have a lock!")

	// Sleep and check the remaining TTL.
	time.Sleep(50 * time.Millisecond)
	if ttl, err := lock.TTL(); err != nil {
		log.Fatalln(err)
	} else if ttl > 0 {
		fmt.Println("Yay, I still have my lock!")
	}

	// Extend my lock.
	if err := lock.Refresh(100*time.Millisecond, nil); err != nil {
		log.Fatalln(err)
	}

	// Sleep a little longer, then check.
	time.Sleep(100 * time.Millisecond)
	if ttl, err := lock.TTL(); err != nil {
		log.Fatalln(err)
	} else if ttl == 0 {
		fmt.Println("Now, my lock has expired!")
	}

}

Documentation

Full documentation is available on GoDoc

About

Simplified distributed locking implementation using Redis

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 98.8%
  • Makefile 1.2%