ratelimit

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2024 License: MIT Imports: 7 Imported by: 0

README

ratelimit

The ratelimit package provides a distributed token bucket rate limiter for Go using Redis. When redis is not available, the rate limiter will fallback to a local in-memory rate limiter using the golang.org/x/time/rate package.

Usage

Import the package:

import "github.com/chuxin0816/ratelimit"
go get "github.com/chuxin0816/ratelimit"

Example

	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	if err := rdb.Ping(context.Background()).Err(); err != nil {
		panic(err)
	}
    
    // create a bucket with a capacity of 100 tokens and a fill rate of 200 tokens per second
    bucket := NewBucket(rdb, "tokenBucket", 100, 200)

    // consume 1 tokens from the bucket
    if !bucket.Take() {
        fmt.Println("rate limited")
    }

    // consume 10 tokens from the bucket
    if !bucket.TakeN(10) {
        fmt.Println("rate limited")
    }

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bucket

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

func NewBucket

func NewBucket(rdb rediser, key string, rate, capacity int) *Bucket

func (*Bucket) Take

func (b *Bucket) Take() bool

func (*Bucket) TakeN

func (b *Bucket) TakeN(count int) bool

Jump to

Keyboard shortcuts

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