go_limiter

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2022 License: Apache-2.0 Imports: 5 Imported by: 0

README

go-limiter

Easy-to-use distributed multi-function current limiter.

Installation

Run the following command under your project:

go get -u github.com/NICEXAI/go-limiter

Usage
  1. Use the NewLimiterByMemory or NewLimiterByRedis methods to initialize a Limiter
// Better performance, but no support for distributed
limiter := NewLimiterByMemory()

// or

// Distributed calls are supported, but depend on redis
client := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"})
limiter := NewLimiterByRedis(client)
  1. Rate limit, for example: allow up to 20 requests per second
key := "test"
rate := limiter.NewRate(20, 1*time.Second)
if rate.Allow(key) {
    // normal business process
} else {
    // abnormal business process
}
  1. Limit concurrency, for example: a single user can initiate a maximum of 10 requests at a time
key := "test"
bucket := limiter.NewBucket(10)
token, ok := bucket.Get(key)
if ok {
    // normal business process
    ...
    // note: be sure to release the token after use
    token.Free()
} else {
    // abnormal business process
}

If you wish to free all the tokens, you can use the bucket.FreeAll() method to free it.

Documentation

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
}

func NewLimiterByMemory

func NewLimiterByMemory() *Limiter

func NewLimiterByRedis

func NewLimiterByRedis(client *redis.Client) *Limiter

func (*Limiter) NewBucket

func (l *Limiter) NewBucket(burst uint) *bucket.Bucket

func (*Limiter) NewRate

func (l *Limiter) NewRate(limit uint, period time.Duration) *rate.Rate

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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