GO语言基于redsync实现分布式锁
package main import ( "fmt" goredislib "github.com/go-redis/redis/v8" "github.com/go-redsync/redsync/v4" "github.com/go-redsync/redsync/v4/redis/goredis/v8" "sync" "time" ) func main() { // Create a pool with go-redis (or redigo) which is the pool redisync will // use while communicating with Redis. This can also be any pool that // implements the `redis.Pool` interface. client := goredislib.NewClient(&goredislib.Options{ Addr: "192.168.0.104:6379", }) pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...) // Create an instance of redisync to be used to obtain a mutual exclusion // lock. rs := redsync.New(pool) wg := sync.WaitGroup{} wg.Add(2) for i := 0; i < 2; i++ { go func() { defer wg.Done() mutexname := "my-global-mutex" mutex := rs.NewMutex(mutexname) fmt.Println("开始锁") if err := mutex.Lock(); err != nil { panic(err) } fmt.Println("锁成功") time.Sleep(2 * time.Second) fmt.Println("解锁") if ok, err := mutex.Unlock(); !ok || err != nil { panic("unlock failed") } }() } wg.Wait() }
发表评论