当前位置:网站首页>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 .
边栏推荐
- How to reduce the font size of custom controls (optimize the round dot progress bar)
- 生成订单30分钟未支付,则自动取消,该怎么实现?
- Add information on the left and add parts on the right of the status bar
- Contentresolver, get the SMS content
- 【无标题】
- placeholder
- Scala sample class case calculate
- [microservices sentinel] sentinel quick start | building an image | starting the console
- adb shell getevent
- Thingsboard - rest API obtains and refreshes tokens
猜你喜欢

The acceleration of 100 km is only 5.92 seconds, and the willanda high-performance version leads with the strength of high-energy products

2022 simulated 100 questions of safety officer-c certificate examination and online simulated examination

Zuckerberg demonstrated four VR head display prototypes, and meta revealed the "family" of metauniverse

Easy to wear - drop down radio

Punch smart spirit 1. The brand is attractive. What is the strength of the product?
![[redis realizes seckill business ③] specific implementation of optimistic lock for oversold problem](/img/01/5ec4e5dae1748dce3d5dee33a24b0b.png)
[redis realizes seckill business ③] specific implementation of optimistic lock for oversold problem
![[redis realizes seckill service ④] one order for one person, and cannot be purchased repeatedly](/img/75/bc588eb4e54899e93cc7df62e45820.png)
[redis realizes seckill service ④] one order for one person, and cannot be purchased repeatedly

移动安全工具-jar

重磅:国产IDE发布,由阿里研发,完全开源!(高性能+高定制性)

Simulation questions and answers of the latest national fire facility operator (senior fire facility operator) in 2022
随机推荐
The problem of multiple callback of video ads stimulated by applets (offcolse problem)
EVM简略
vb学习什么[通俗易懂]
【Redis实现秒杀业务④】一人一单,不可重复购买
移动安全工具-apktool
2022年全国最新消防设施操作员(高级消防设施操作员)模拟题及答案
Examination questions and mock examination for safety management personnel of hazardous chemical business units in 2022
[redis realizes seckill business ③] specific implementation of optimistic lock for oversold problem
I'd like to ask how to open an account at industrial securities? Is it safe to open a stock account through the link
Introduction to smart contract security audit delegatecall (2)
activity生命周期
2021-04-18
[untitled]
Preliminary understanding of qtoolbutton
C#和C 的CAN通信实验
Several ways for wechat applet to jump to the page are worth collecting
【无标题】
I brush the question I - copy the linked list with random pointer
LLVM TargetPassConfig
The picture of wechat official account can not be displayed normally