当前位置:网站首页>Golang example renewal lock: redis+channel+sync Mutex

Golang example renewal lock: redis+channel+sync Mutex

2022-06-25 01:07:00 Game programming

package mainimport (    "context"    "fmt"    "github.com/go-redis/redis"    "golang.org/x/sync/errgroup"    "log"    "sync"    "time")func main() {    NewRedis()    fu1()    time.Sleep(100 * time.Second)}var rdb *redis.Clientvar ctx = context.Background()var mutex sync.Mutexfunc NewRedis() {    rdb = redis.NewClient(&redis.Options{        Addr:     "127.0.0.1:6379",        Password: "", // no password set        DB:       0,  // use default DB    })}func Lock(key string) error {    mutex.Lock()    defer mutex.Unlock()    _, err := rdb.SetNX(key, 1, 1*time.Second).Result()    if err != nil {        log.Println(err.Error())    }    return err}func UnLock(key string) error {    _, err := rdb.Del(key).Result()    if err != nil {        log.Println(err.Error())        return err    }    return err}func Expire(key string) error {    _, err := rdb.Expire(key, 1*time.Second).Result()    if err != nil {        log.Println(err.Error())        return err    }    return err}func fu1() error {    ch := make(chan bool)    //  Lock     err := Lock("lock_key")    if err != nil {        return err    }    // Unlock     defer func() {        err = UnLock("lock_key")        if err != nil {            fmt.Println(err.Error())            return        }        fmt.Println("release redis lock success")    }()    g, _ := errgroup.WithContext(context.Background())    //... Main business code     g.Go(func() error {        time.Sleep(15 * time.Second)        ch <- true        return nil    })    // Lock renewal     g.Go(func() error {        ticker := time.NewTicker(time.Second * 1)        for {            select {            //  The task is not finished yet   Renew per second             case <-ticker.C:                Expire("lock_key")                fmt.Println(time.Now())                // Received the completed  channel  Just shut it down time Timing task             case <-ch:                ticker.Stop()                return nil            }        }    })    // Wait for the semaphore     if err = g.Wait(); err != nil {        return err    }    close(ch)    return nil}

author :Hello

Game programming , A game development favorite ~

If the picture is not displayed for a long time , Please use Chrome Kernel browser .

原网站

版权声明
本文为[Game programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206242012409013.html