This package is based on rwz/redis-gcra and implements GCRA (aka leaky bucket) for rate limiting based on Redis. The code requires Redis version 3.2 or newer since it relies on replicate_commands feature.
redis_rate requires a Go version with Modules support and uses import versioning. So please make sure to initialize a Go module before installing redis_rate:
go mod init github.com/my/repo
go get github.com/go-redis/redis_rate/v8
Import:
import "github.com/go-redis/redis_rate/v8"
package redis_rate_test
import (
"fmt"
"github.com/go-redis/redis/v7"
"github.com/go-redis/redis_rate/v8"
)
func ExampleNewLimiter() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
_ = rdb.FlushDB().Err()
limiter := redis_rate.NewLimiter(rdb)
res, err := limiter.Allow("project:123", redis_rate.PerSecond(10))
if err != nil {
panic(err)
}
fmt.Println(res.Allowed, res.Remaining)
// Output: true 9
}