ratelimiter

package module
v0.0.0-...-f8d22f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 20, 2016 License: MIT Imports: 5 Imported by: 0

README

go-redis-ratelimiter

Simple go ratelimiter library with redis backend

Docs

https://godoc.org/github.com/oeegor/go-redis-ratelimiter

Usage


import (
	"github.com/garyburd/redigo/redis"
    "github.com/oeegor/go-redis-ratelimiter"
)

func main() {

    // initialize redis pool
    redisPool := redis.NewPool(func() (redis.Conn, error) {
		c, err := redis.Dial("tcp", "your-redis-address")
		if err != nil {
			return nil, err
		}
		return c, err
	}, 100)  // also set max connections to 100

    // increment rate limit usage for given key that is allowed 10 requests per second with one try
    // Ratelimiter will try to acquire limit N tries using time.Sleep between tries
    limitCtx, err := ratelimiter.Incr(redisPool, "mykey", 10, time.Second, 1)

    if err != nil {
        // do something
    }

    // limitCtx contains all necessary data for ratelimiter state
    if limitCtx.Reached() {
        // code to handle over the limit logic
    }
}

Documentation

Overview

Package ratelimiter provides possibility to check rate limit usage by given resource with given allowed rate and time interval. It uses redis as backend so can be used to check ratelimit for distributed instances of your app.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LimitCtx

type LimitCtx struct {
	// ported from here: http://flask.pocoo.org/snippets/70/
	ExpireAt  int64
	Key       string
	Limit     int
	Per       time.Duration
	Current   int
	Tries     int
	RedisPool *redis.Pool
}

func BuildLimiter

func BuildLimiter(redisPool *redis.Pool, key string, limit int, per time.Duration, tries int) *LimitCtx

Initializes new LimiterCtx instance which then can be used to increment and check ratelimit usage

func Incr

func Incr(redisPool *redis.Pool, name string, limit int, period time.Duration, retries int) (*LimitCtx, error)

Shorthand function to increment resource usage and to get LimiterCtx back. Wrapper around BuildLimiter and LimiterCtx.Incr

func (*LimitCtx) Incr

func (self *LimitCtx) Incr() error

Increments rate limit counter

func (*LimitCtx) Reached

func (self *LimitCtx) Reached() bool

Returns whether limit has been reached or not

func (*LimitCtx) Remaining

func (self *LimitCtx) Remaining() int

Returns how many times resource can be used before reaching limit

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL