网络编程
位置:首页>> 网络编程>> Go语言>> go redis实现滑动窗口限流的方式(redis版)

go redis实现滑动窗口限流的方式(redis版)

作者:陶士涵  发布时间:2024-02-02 18:04:27 

标签:go,redis,限流

之前给大家介绍过单机当前进程的滑动窗口限流 , 这一个是使用go redis list结构实现的滑动窗口限流 , 原理都一样 , 但是支持分布式

原理可以参考之前的文章介绍


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保证当前程序不存在并发冲突问题


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

来源:https://www.cnblogs.com/taoshihan/archive/2020/12/14/14134840.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com