-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
53 lines (44 loc) · 990 Bytes
/
main.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"context"
"log"
"time"
"github.com/go-redis/redis/v8"
"github.com/sonirico/pacemaker"
)
func main() {
ctx := context.Background()
redisOpts, err := redis.ParseURL("redis://localhost:6379/0")
if err != nil {
panic(err)
}
redisCli := redis.NewClient(redisOpts)
const (
tokensPerMinute = 1000
tokensPerRequest = 100
// 1 minute rate limit windows
rateAmount = 1
rateUnit = time.Minute
)
rateLimiter := pacemaker.NewTokenFixedWindowRateLimiter(
pacemaker.NewFixedWindowRateLimiter(pacemaker.FixedWindowArgs{
Capacity: tokensPerMinute,
Rate: pacemaker.Rate{
Amount: rateAmount,
Unit: rateUnit,
},
Clock: pacemaker.NewClock(),
DB: pacemaker.NewFixedWindowRedisStorage(
redisCli,
pacemaker.FixedWindowRedisStorageOpts{
Prefix: "pacemaker",
},
),
}),
)
for i := 0; i < 100; i++ {
ttw, err := rateLimiter.Try(ctx, tokensPerRequest)
log.Println(ttw, err)
time.Sleep(time.Second)
}
}