redsync:基于Redis的分布式互斥锁Go实现

Distributed mutual exclusion lock using Redis for Go

分支3Tags51
文件最后提交记录最后更新时间
7 天前
6 个月前
3 个月前
2 年前
8 个月前
5 年前
2 年前
7 天前
7 天前
10 年前
2 年前
2 年前
10 天前
10 天前
3 个月前
1 年前
1 年前
1 年前
9 个月前
9 个月前

Redsync

Go Reference CI

Redsync 为 Go 提供基于 Redis 的分布式互斥锁实现,如这篇文章中所述。由 antirez 提供的 Ruby 参考库可在 github.com/antirez/redlock-rb 获取。

安装

使用 go get 命令安装 Redsync:

$ go get github.com/go-redsync/redsync/v4

将安装两种驱动实现;不过,只有实际使用的那个会被包含到你的项目中。

参阅 examples 目录,查看各驱动的用法。

文档

使用

为保持示例简洁,错误处理被简化为 panic。

package main

import (
	goredislib "github.com/redis/go-redis/v9"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v9"
)

func main() {
	// Create a pool with go-redis (or redigo) which is the pool redsync will
	// use while communicating with Redis. This can also be any pool that
	// implements the `redis.Pool` interface.
	client := goredislib.NewClient(&goredislib.Options{
		Addr: "localhost:6379",
	})
	pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)

	// Create an instance of redsync to be used to obtain a mutual exclusion
	// lock.
	rs := redsync.New(pool)

	// Obtain a new mutex by using the same name for all instances wanting the
	// same lock.
	mutexname := "my-global-mutex"
	mutex := rs.NewMutex(mutexname)

	// Obtain a lock for our given mutex. After this is successful, no one else
	// can obtain the same lock (the same mutex name) until we unlock it.
	if err := mutex.Lock(); err != nil {
		panic(err)
	}

	// Do your work that requires the lock.

	// Release the lock so other processes or threads can obtain a lock.
	if ok, err := mutex.Unlock(); !ok || err != nil {
		panic("unlock failed")
	}
}

贡献

欢迎提交贡献。

许可证

Redsync 采用 BSD(三条款)许可证 发布。

免责声明

本代码实现的算法目前仍处于提案阶段,尚未进行正式分析。请在生产环境中使用之前,确保理解其工作原理。

实际应用场景

以下是使用 Redsync 的公开开源项目列表:

  • Sourcegraph:通用代码搜索和智能平台。在其内部缓存实现中使用 Redsync。
  • Open Match(由 Google 提供):灵活、可扩展且支持水平扩展的视频游戏匹配服务。在其状态存储实现中使用 Redsync。
  • Gocron(由 go-co-op 提供):gocron 是一个分布式作业调度包,让你可以使用简洁、易读的语法,以预设时间间隔运行 Go 函数。在其分布式作业调度器实现中使用 Redsync。

如果你在项目中使用了 Redsync,请提交一个拉取请求,将其添加到列表中。

项目介绍

分布式互斥锁使用Redis实现,适用于Go语言环境【此简介由AI生成】

定制我的领域
234.05 K350访问 GitHub