当前位置:网站首页>Golang示例续期锁:Redis+Channel+sync.Mutex
Golang示例续期锁:Redis+Channel+sync.Mutex
2022-06-24 20:12:00 【游戏编程】
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) // 加锁 err := Lock("lock_key") if err != nil { return err } //解锁 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()) //...主业务代码 g.Go(func() error { time.Sleep(15 * time.Second) ch <- true return nil }) //锁续期 g.Go(func() error { ticker := time.NewTicker(time.Second * 1) for { select { // 任务还没执行完 每秒续期 case <-ticker.C: Expire("lock_key") fmt.Println(time.Now()) //收到执行完的 channel 就关闭time定时任务 case <-ch: ticker.Stop() return nil } } }) //等待信号量 if err = g.Wait(); err != nil { return err } close(ch) return nil}作者:Hello
游戏编程,一个游戏开发收藏夹~
如果图片长时间未显示,请使用Chrome内核浏览器。
边栏推荐
- Simple collation of Web cache
- Qiniu cloud uploads video to get the first frame of video
- 2021-09-12
- Kibana installation via kubernetes visual interface (rancher)
- Network request -volley
- 2021-11-05
- Meta & Berkeley proposed a universal multi-scale visual transformer based on pooled self attention mechanism. The classification accuracy in Imagenet reached 88.8%! Open source
- Tiktok wallpaper applet, starlight wallpaper applet version 2.0, upgraded version
- Usage of ViewModel and livedata in jetpack
- 2021-11-07
猜你喜欢

JMeter socket connection sends data
5-minute NLP: summary of 3 pre training libraries for rapid realization of NER

在企业级开发过程中我发现有位同事用select * from where 条件 for update

移动安全工具-jar

【Redis实现秒杀业务③】超卖问题之乐观锁具体实现

ros(24):error: invalid initialization of reference of type ‘xx’ from expression of type ‘xx’

Technologie des fenêtres coulissantes en octets dans la couche de transmission
![[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS](/img/fc/6b36759570b9b1007d2640009576d9.png)
[micro service sentinel] real time monitoring | RT | throughput | concurrency | QPS

UE4 WebBrowser chart cannot display problems

Single blind box removal, social blind box and friend blind box program source code
随机推荐
[Solved] Public key for mysql-community-xxx. rpm is not installed
adb shell getevent
Using tcp/udp tools to debug the yeelight ribbon
Previous basic review
Custom animation (simulated win10 loading animation)
[microservices sentinel] cluster link | microservices cluster environment construction
Custom animation (simulated win10 loading animation) - Optimization
In the process of enterprise development, I found that a colleague used the select * from where condition for update
ros(24):error: invalid initialization of reference of type ‘xx’ from expression of type ‘xx’
Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
December 6, 2019 what happens after the browser enters a URL
redis + lua实现分布式接口限流实现方案
Uniapp encapsulated incentive advertisement, screen insert advertisement and banner advertisement
Mobile security tool -dex2jar
Leetcode 1248. 统计「优美子数组」(害,突然发现只会暴力枚举了)
【微服务|Sentinel】Sentinel快速入门|构建镜像|启动控制台
2021-11-05
Design scheme of authority management of fusion model
ros(25):rqt_image_view报错Unable to load plugin for transport ‘compressed‘, error string
A website for programmers with a monthly salary of 30K