之前給大家介紹過單機當前進程的滑動窗口限流 , 這一個是使用go redis list結構實現的滑動窗口限流 , 原理都一樣 , 但是支持分布式
原理可以參考之前的文章介紹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
func LimitFreqs(queueName string, count uint, timeWindow int64) bool { currTime := time .Now().Unix() length := uint(ListLen(queueName)) if length < count { ListPush(queueName, currTime) return true } // 隊列滿了,取出最早訪問的時間 earlyTime, _ := strconv.ParseInt(ListIndex(queueName, int64(length)-1), 10, 64) // 說明最早期的時間還在時間窗口內,還沒過期,所以不允許通過 if currTime-earlyTime <= timeWindow { return false } else { // 說明最早期的訪問應該過期了,去掉最早期的 ListPop(queueName) ListPush(queueName, currTime) } return true } |
開源作品
開源GO語言在線WEB客服即時通訊管理系統GO-FLY
github地址:go-fly
在線測試地址:https://gofly.sopans.com
附錄:下面看下redis分布式鎖的go-redis實現
在分布式的業務中 , 如果有的共享資源需要安全的被訪問和處理 , 那就需要分布式鎖
分布式鎖的幾個原則;
1.「鎖的互斥性」:在分布式集群應用中,共享資源的鎖在同一時間只能被一個對象獲取。
2. 「可重入」:為了避免死鎖,這把鎖是可以重入的,并且可以設置超時。
3. 「高效的加鎖和解鎖」:能夠高效的加鎖和解鎖,獲取鎖和釋放鎖的性能也好。
4. 「阻塞、公平」:可以根據業務的需要,考慮是使用阻塞、還是非阻塞,公平還是非公平的鎖。
redis實現分布式鎖主要靠setnx命令
1. 當key存在時失敗 , 保證互斥性
2.設置了超時 , 避免死鎖
3.利用mutex保證當前程序不存在并發沖突問題
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package redis import ( "context" "github.com/go-redis/redis/v8" "github.com/taoshihan1991/miaosha/setting" "log" "sync" "time" ) var rdb *redis.Client var ctx = context.Background() var mutex sync.Mutex func NewRedis() { rdb = redis.NewClient(&redis.Options{ Addr: setting.Redis.Ip + ":" + setting.Redis.Port, Password: "", // no password set DB: 0, // use default DB }) } func Lock(key string) bool { mutex.Lock() defer mutex.Unlock() bool, err := rdb.SetNX(ctx, key, 1, 10*time.Second).Result() if err != nil { log.Println(err.Error()) } return bool } func UnLock(key string) int64 { nums, err := rdb.Del(ctx, key).Result() if err != nil { log.Println(err.Error()) return 0 } return nums } |
開源作品
開源GO語言在線WEB客服即時通訊管理系統GO-FLY
github地址:go-fly
在線測試地址:https://gofly.sopans.com
到此這篇關于go redis實現滑動窗口限流-redis版的文章就介紹到這了,更多相關go redis滑動窗口限流內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/taoshihan/archive/2020/12/14/14134840.html