rateLimit := pacemaker.NewTokenFixedWindowRateLimiter(
pacemaker.NewFixedTruncatedWindowRateLimiter(
pacemaker.FixedTruncatedWindowArgs{
Capacity: cfg.Capacity,
Rate: pacemaker.Rate{
Unit: cfg.Rate.Unit,
Amount: cfg.Rate.Amount,
},
Clock: cfg.Clock,
DB: pacemaker.NewFixedWindowRedisStorage(
cfg.RedisCli,
pacemaker.FixedWindowRedisStorageOpts{
Prefix: cfg.Bucket,
},
),
},
),
)
result, err := rateLimit.Try(context.Background(), 1)
if err != nil {
log.Errorf("error try: '%v'", err)
}
log.Debugf("Try Result: '%v'", result)
result, err = rateLimit.Check(context.Background(), 1)
if err != nil {
log.Errorf("error try: '%v'", err)
}
log.Debugf("Check Result: '%v'", result)
$ go run examples/rate_limits/main.go
2022-11-04T12:48:03Z - DEBUG - {"service":"example"} - connected to redis
2022-11-04T12:48:03Z - DEBUG - {"service":"example"} - Try Result: '{0s 159990}'
2022-11-04T12:48:03Z - DEBUG - {"service":"example"} - Check Result: '{0s 159990}'
$ go run examples/rate_limits/main.go
2022-11-04T12:48:07Z - DEBUG - {"service":"example"} - connected to redis
2022-11-04T12:48:07Z - DEBUG - {"service":"example"} - Try Result: '{0s 159989}'
2022-11-04T12:48:07Z - DEBUG - {"service":"example"} - Check Result: '{0s 159989}'
$ go run examples/rate_limits/main.go
2022-11-04T12:48:24Z - DEBUG - {"service":"example"} - connected to redis
2022-11-04T12:48:24Z - DEBUG - {"service":"example"} - Try Result: '{0s 159988}'
$ go run examples/rate_limits/main.go
2022-11-04T12:48:42Z - DEBUG - {"service":"example"} - connected to redis
2022-11-04T12:48:42Z - DEBUG - {"service":"example"} - Check Result: '{0s 160000}'
$ go run examples/rate_limits/main.go
2022-11-04T12:48:45Z - DEBUG - {"service":"example"} - connected to redis
2022-11-04T12:48:45Z - DEBUG - {"service":"example"} - Check Result: '{0s 160000}'
$ go run examples/rate_limits/main.go
2022-11-04T12:49:03Z - DEBUG - {"service":"example"} - connected to redis
2022-11-04T12:49:03Z - DEBUG - {"service":"example"} - Try Result: '{0s 159987}'
2022-11-04T12:49:03Z - DEBUG - {"service":"example"} - Check Result: '{0s 159987}'
If we run both(try/check) the returned value by Check method is correct.
If we run only the check method, the returned value of Check methods is the capacity of the bucket instead of the remaining value.