Documentation
¶
Overview ¶
Package ratelimiter provides the fastest abstract rate limiter, base on redis.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter struct.
func New ¶
New returns a Limiter instance with given options. If options.Client omit, the limiter is a memory limiter
func (*Limiter) Get ¶
Get get a limiter result for id. support custom limiter policy.
Get get a limiter result:
userID := "user-123456"
res, err := limiter.Get(userID)
if err == nil {
fmt.Println(res.Reset) // 2016-10-11 21:17:53.362 +0800 CST
fmt.Println(res.Total) // 100
fmt.Println(res.Remaining) // 100
fmt.Println(res.Duration) // 1m
}
Get get a limiter result with custom limiter policy:
id := "id-123456"
policy := []int{100, 60000, 50, 60000, 50, 120000}
res, err := limiter.Get(id, policy...)
type Options ¶
type Options struct {
Max int // The max count in duration for no policy, default is 100.
Duration time.Duration // Count duration for no policy, default is 1 Minute.
Prefix string // Redis key prefix, default is "LIMIT:".
Client RedisClient // Use a redis client for limiter, if omit, it will use a memory limiter.
}
Options for Limiter
type RedisClient ¶ added in v0.3.0
type RedisClient interface {
RateDel(string) error
RateEvalSha(string, []string, ...interface{}) (interface{}, error)
RateScriptLoad(string) (string, error)
}
RedisClient defines a redis client struct that ratelimiter need. Examples: https://github.com/teambition/ratelimiter-go/blob/master/ratelimiter_test.go#L18
Implements RedisClient for a simple redis client:
import "gopkg.in/redis.v4"
type redisClient struct {
*redis.Client
}
func (c *redisClient) RateDel(key string) error {
return c.Del(key).Err()
}
func (c *redisClient) RateEvalSha(sha1 string, keys []string, args ...interface{}) (interface{}, error) {
return c.EvalSha(sha1, keys, args...).Result()
}
func (c *redisClient) RateScriptLoad(script string) (string, error) {
return c.ScriptLoad(lua).Result()
}
Implements RedisClient for a cluster redis client:
import "gopkg.in/redis.v4"
type clusterClient struct {
*redis.ClusterClient
}
func (c *clusterClient) RateDel(key string) error {
return c.Del(key).Err()
}
func (c *clusterClient) RateEvalSha(sha1 string, keys []string, args ...interface{}) (interface{}, error) {
return c.EvalSha(sha1, keys, args...).Result()
}
func (c *clusterClient) RateScriptLoad(script string) (string, error) {
var sha1 string
err := c.ForEachMaster(func(client *redis.Client) error {
res, err := client.ScriptLoad(script).Result()
if err == nil {
sha1 = res
}
return err
})
return sha1, err
}
Uses it:
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
limiter := ratelimiter.New(ratelimiter.Options{Client: redisClient{client}})