提交 f97f0e13 authored 作者: mooncake9527's avatar mooncake9527

限速器

1.基于ip 2.滑动窗口算法 3.分布式 基于redis同步
上级 d65f514e
package sync_ratelimiter package sync_ratelimiter
import ( import (
"context"
"fmt" "fmt"
"github.com/RussellLuo/slidingwindow" "github.com/RussellLuo/slidingwindow"
"github.com/go-redis/redis" "github.com/redis/go-redis/v9"
"strconv" "strconv"
"sync" "sync"
"time" "time"
...@@ -20,17 +21,17 @@ func (d *RedisDatastore) fullKey(key string, start int64) string { ...@@ -20,17 +21,17 @@ func (d *RedisDatastore) fullKey(key string, start int64) string {
func (d *RedisDatastore) Add(key string, start, value int64) (int64, error) { func (d *RedisDatastore) Add(key string, start, value int64) (int64, error) {
k := d.fullKey(key, start) k := d.fullKey(key, start)
c, err := d.client.IncrBy(k, value).Result() c, err := d.client.IncrBy(context.Background(), k, value).Result()
if err != nil { if err != nil {
return 0, err return 0, err
} }
_, _ = d.client.Expire(k, d.ttl).Result() _, _ = d.client.Expire(context.Background(), k, d.ttl).Result()
return c, err return c, err
} }
func (d *RedisDatastore) Get(key string, start int64) (int64, error) { func (d *RedisDatastore) Get(key string, start int64) (int64, error) {
k := d.fullKey(key, start) k := d.fullKey(key, start)
value, err := d.client.Get(k).Result() value, err := d.client.Get(context.Background(), k).Result()
if err != nil { if err != nil {
if err == redis.Nil { if err == redis.Nil {
err = nil err = nil
......
...@@ -14,9 +14,10 @@ func TestRateLimiter(t *testing.T) { ...@@ -14,9 +14,10 @@ func TestRateLimiter(t *testing.T) {
rl := NewIPRateLimiter( rl := NewIPRateLimiter(
WithWindowSize(1*time.Second), WithWindowSize(1*time.Second),
WithMaxRequests(4), WithMaxRequests(4),
WithRedisAddr("localhost:6379"), //WithRedisAddr("localhost:6379"),
WithRedisAddr("r-bp1fm63ps25tp3k0vypd.redis.rds.aliyuncs.com:6379"),
WithRedisDB(0), WithRedisDB(0),
WithRedisPassword(""), WithRedisPassword("$3ktkf6z8m"),
) )
ip := "192.168.1.1" ip := "192.168.1.1"
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论