Distributed mutual exclusion lock using Redis for Go
This repository is empty
Translated by AI, submit an issue feedback
Redsync
Redsync 提供了一个基于 Redis 的分布式互斥锁实现,适用于 Go 语言,其设计思路如 这篇文章 所述。Ruby 语言的参考库(由 antirez 开发)可在 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 (3-Clause) 许可协议 开源。
免责声明
本代码实现的算法目前仍处于提案阶段,尚未经过正式的分析验证。在生产环境中使用前,请务必充分了解其工作原理。
实际应用案例
以下是一些使用 Redsync 的公开开源项目列表:
- Sourcegraph:通用代码搜索与智能平台。在内部缓存实现中使用 Redsync。
- Google 的 Open Match:灵活、可扩展且具备高 scalability 的视频游戏匹配系统。在其状态存储实现中使用 Redsync。
- go-co-op 的 Gocron:gocron 是一个分布式任务调度包,允许您使用简单、人性化的语法按预定时间间隔运行 Go 函数。在其分布式任务调度器实现中使用 Redsync。
如果您的项目中使用了 Redsync,请提交 pull request 将其添加到列表中。