redistb

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2024 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package redistb implements a token bucket using Redis.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RedisClient

type RedisClient interface {
	// Required to load and execute scripts
	Eval(script string, keys []string, args ...interface{}) *redis.Cmd
	EvalSha(sha1 string, keys []string, args ...interface{}) *redis.Cmd
	ScriptExists(hashes ...string) *redis.BoolSliceCmd
	ScriptLoad(script string) *redis.StringCmd
}

RedisClient is an interface that encompasses the various methods used by TokenBucket, and allows selecting among different Redis client implementations (e.g. regular Redis, Redis Cluster, sharded, etc.)

type TokenBucket

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

TokenBucket implements a token-bucket limiter stored in a Redis database. It supports atomic operation with concurrent access.

func New

func New(client RedisClient) *TokenBucket

New returns a new TokenBucket that uses the provided Redis client.

func (*TokenBucket) Call

func (tb *TokenBucket) Call(
	ctx context.Context,
	prefix string,
	capacity int64,
	replenishRate float64,
	numTokens int,
) (bool, int64, error)

Call implements the actual token bucket algorithm. Given a bucket with capacity `capacity` and replenishment rate of `replenishRate` tokens per second, it will first ensure that the bucket has the correct number of tokens added (up to the maximum capacity) since the last time that this function was called. Then, it will attempt to remove `numTokens` from the bucket.

This function returns a boolean indicating whether it was able to remove all tokens from the bucket, the remaining number of tokens in the bucket, and any error that occurs.

func (*TokenBucket) Load

func (tb *TokenBucket) Load(ctx context.Context) error

Load preloads any required Lua scripts into the Redis database, and updates the hash of the resulting script. Calling this function is optional, but will greatly reduce the network traffic to the Redis cluster since it only needs to pass a hash of the script and not the full script content.

func (*TokenBucket) Reset

func (tb *TokenBucket) Reset(ctx context.Context, prefix string) error

Reset resets the token bucket for the given prefix.

Jump to

Keyboard shortcuts

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