ratelimiter

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2016 License: MIT Imports: 4 Imported by: 0

README

ratelimiter

Build Status GoDoc Go Report Card Coverage

ratelimiter is a redis-based ratecounter and ratelimiter

Tutorial

package main

import (
    "github.com/abo/ratelimiter"
)

...

func main() {
    pool := newRedisPool("localhost:6379", "")
    
    // Counter
    counter := ratelimiter.NewCounter(pool, "rl:test", 10 * time.Minute, 15 * time.Second)
    counter.Inc("click")
    c, err := counter.Count("click")
    
    // Limiter
    limiter := ratelimiter.NewLimiter(pool, "rl:test", 1 * time.Hour, 15 * time.Minute, 100)
    limiter.Inc("114.255.86.200")
    rem, err := limiter.Remaining("114.255.86.200")
    exceed, err := limiter.Exceeded("114.255.86.200")
}

Installation

Install ratelimiter using the "go get" command:

go get github.com/abo/ratelimiter

Documentation

Contributing

WELCOME

License

ratelimiter is available under the The MIT License (MIT).

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Counter

type Counter struct {
	// contains filtered or unexported fields
}

Counter count total occurs during a time window w, it will store occurs during every time slice s: (now ~ now - s), (now - s ~ now - 2*s)...

func NewCounter

func NewCounter(pool Pool, pfx string, w, s time.Duration) *Counter

NewCounter create a new Counter

func (*Counter) Count

func (c *Counter) Count(id string) (int64, error)

Count return total occurs in period of Counter.w

func (*Counter) Inc

func (c *Counter) Inc(id string) error

Inc increment id's occurs with current timestamp, the count before Counter.w will be cleanup

func (*Counter) Reset

func (c *Counter) Reset(id string) error

Reset cleanup occurs, set it to zero

type Limiter

type Limiter struct {
	Counter
	// contains filtered or unexported fields
}

Limiter a redis-based ratelimiter

func NewLimiter

func NewLimiter(pool Pool, pfx string, w, s time.Duration, n int64) *Limiter

NewLimiter create a new redis-based ratelimiter the Limiter limits the rate to n times per w

func (*Limiter) Exceeded

func (l *Limiter) Exceeded(id string) (bool, error)

Exceeded exceeded the rate limit or not

func (*Limiter) Remaining

func (l *Limiter) Remaining(id string) (int64, error)

Remaining return the number of requests left for the time window

type Pool

type Pool interface {
	Get() redis.Conn
}

Pool maintains a pool of connections. The application calls the Get method to get a connection from the pool and the connection's Close method to return the connection's resources to the pool.

Jump to

Keyboard shortcuts

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