gocache

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 15 Imported by: 0

README

gocache

Go Report Card Build Status GoDoc GitHub license

Inspired by the Laravel Cache implementation, this package provides a store agnostic caching system via an expressive and unified interface that allows for an abstraction layer between different data store drivers and your application. This enables for each store to be used interchangeably without any code changes other than the programmatic configuration of the desired store(s).

Table Of Contents

Installation

To start using this package in your application simply run:go get -u github.com/alejandro-carstens/gocache

Configuration

This package supports 3 backends out of the box: Redis, Memcached and Local (via go-cache). Each store has a specific configuration whose parameters can be easily referenced in the following GoDoc sections:

Usage

Obtaining A Cache Instance

In order to new up a cache implementation simply call gocache.New with the desired configuration and encoder:

// Redis
cache, err := gocache.New(&gocache.RedisConfig{
    Prefix: "gocache:",
    Addr:   "localhost:6379",
}, encoder.JSON{})
// handle err

// Memcache
cache, err := gocache.New(&gocache.MemcacheConfig{
    Prefix:  "gocache:",
    Servers: []string{"127.0.0.1:11211"},
}, encoder.Msgpack{})
// handle err

// Local
cache, err := gocache.New(&gocache.LocalConfig{
    Prefix:          "gocache:",
    DefaultInterval: time.Second,
}, encoder.JSON{})
// handle err
Retrieving Items From The Cache

All methods including the prefix Get are used to retrieve items from the cache. If an item does not exist in the cache for the given key an error of type gocache.ErrNotFound will be raised. Please see the following examples:


v, err := cache.GetFloat32("temperature")
// handle err

v, err := cache.GetFloat64("height")
// handle err

v, err := cache.GetInt("score")
// handle err

v, err := cache.GetInt64("counter")
// handle err

v, err := cache.GetString("username")
// handle err

v, err := cache.GetUint64("id")
// handle err

// GetBool will return false in the event of the cache entry being
// the string 'false', empty string, boolean false, string '0' or
// the number 0. The value v will be true otherwise.
v, err := cache.GetBool("active")
// handle err

// Get any type e.g. Movie{Name string, Views int64}
var m Movie
err := cache.Get("e.t.", &m)
// handle err

// Handle missed entry for key
v, err := cache.GetString("entry-not-found-key")
if errors.Is(gocache.ErrNotFound, err) {
    // handle err
}

The method Many is also exposed in order to retrieve multiple cache records with one call. The results of the Many invocation will be returned in a map of gocache.Item instances keyed by the retrieved cached entries keys. Please see the example below:

items, err := cache.Many("string", "uint64", "int", "int64", "float64", "float32", "any", "bool")
// handle err

for key, item := range items {
    switch key:
    case "string":
        v, err := item.String()
        // handle err
    case "uint64":
        v, err := item.Uint64()
        // handle err
    case "int":
        v, err := item.Int()
        // handle err
    case "int64":
        v, err := item.Int64()
        // handle err
    case "float64":
        v, err := item.Float64()
        // handle err
    case "float32":
        v, err := item.Float32()
        // handle err
    case "any":
        var m Movie
        err := item.Unmarshal(&m)
        // handle err
    case "bool":
        // Bool will return false in the event of the cache entry being
        // the string 'false', empty string, boolean false, string '0' 
        // or the number 0. The value v will be true otherwise.
        v, err := item.Bool()
        // handle err
    }
}

Storing Items In The Cache

You can use the Put method to store items in the cache with a specified time to live:

err := cache.Put("key", "value", 10 * time.Second)
// handle err

// You can store any value
err := cache.Put("most_watched_movie", &Movie{
    Name:  "Avatar",
    Views: 100,
}, 60 * time.Minute)
// handle err

To atomically add an entry to the cache if the key for the given entry does not exist you can use Add:

added, err := cache.Add("key", 2, time.Minute)
// handle err
if !added {
    // do something
}

To store a value indefinitely (without expiration) simply use the method Forever:

err := cache.Forever("key", "value")
// handle err

To store many values at once you can use PutMany:

var entries = []gocache.Entry{
    {
        Key:   "string",
        Value: "whatever",
        Duration: time.Minute,
    },
    {
        Key:   "any",
        Value: Movie{
          Name:  "Star Wars",
          Views: 10,
        },
        Duration: time.Minute,
    },
}
err := cache.PutMany(entries...)
// handle err

To increment and decrement values (for now you can only increment & decrement using int64 values) simply use Increment & Decrement. Please note that if there is no entry for the key being incremented the initial value will be 0 plus whatever value was passed in and the entry will be set to not expire:

val, err := cache.Increment("a", 1) // a = 1
// handle err

val, err := cache.Increment("a", 10) // a = 11
// handle err

val, err := cache.Decrement("a", 2) // a = 9
// handle err

val, err := cache.Decrement("b", 5) // b = -5
// handle err
Removing Items From The Cache

You may remove items from the cache using the Forget or ForgetMany methods:

// Note that res will be true if the cache entry was removed and false 
// if no entry was for the given key
res, err := cache.Forget("key") 
// handle err

// If no error is returned you can assume all keys where deleted. Not present keys will be
// ignored
err := cache.ForgetMany("key1", "key2", "key3")
// handle err

If you want to clear all entries from the cache you can use the Flush method:

err := cache.Flush()
// handle err

Cache Tags

Storing Cache Tagged Items

Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag. You may access a tagged cache by passing in an ordered sliced of tag names. For example, let's access a tagged cache and put a value into the cache:

err := cache.Tags("person", "artist").Put("John", "Doe", time.Minute)
// handle err

err := cache.Tags("person", "accountant").Put("Jane", "Doe", time.Minute)
// handle err
Accessing Cache Tagged Items

To retrieve a tagged cache item, pass the same ordered list of tags to the Tags method and then call the any of the methods shown in the Retrieving Items From The Cache section above:

v, err := cache.Tags("person", "artist").GetString("John")
// handle err

v, err := cache.Tags("person", "accountant").GetString("Jane")
// handle err
Removing Tagged Cache Items

You may flush all items that are assigned a tag or list of tags. For example, this statement would remove all caches tagged with either person, accountant, or both. So, both Jane and John would be removed from the cache:

err := cache.Tags("person", "accountant").Flush()
// handle err

In contrast, this statement would remove only cached values tagged with accountant, so Jane would be removed, but not John:

err := cache.Tags("accountant").Flush()
// handle err

In addition you can also call Forget:

res, err := cache.Tags("person", "accountant").Forget("Jane")
// handle err

Important Note: with the exception of the Redis driver, when calling Flush with tags, the underlying entries won't be deleted so please make sure to set expiration values when using tags and flushing.

Accessing Tags

In order to interact with tags directly you can call TagSet on a tagged cache:

// Obtain the underlying tagged cache TagSet instance
ts := cache.Tags("person", "accountant").TagSet()

// Hard deletes cache entries used to hold tag set tags
err := ts.Flush()
// handle err

// Returns the tag ids associated with the provided tag set tags 
ids, err := ts.TagIds()
// handle err

// Resets all the tag set tags
err := ts.Reset()

Atomic Locks

Atomic locks allow for the manipulation of distributed locks without worrying about race conditions. An example of this would be that you only want one process to work on one object at a time, such as the same file should only be uploaded one at a time (we do not want the same file to be uploaded more than once at any given time). You may create and manage locks via the Lock method:

var (
    lock          = cache.Lock("merchant_1", "pid_1", 30 * time.Second)
    acquired, err = lock.Acquire()
)
if err != nil {
    // handle err
}
if acquired {
    defer func() {
        // released will be true if the lock was released before expiration
        released, err := lock.Release()
        // handle err
    }
    // do something here
}

The lock Get method accepts a closure. After the closure is executed, the lock will automatically be released:

acquired, err := cache.Lock("merchant_1", "pid_1", 30 * time.Second).Get(func() error {
    // do something cool here
})
// handle err
if !acquired {
    // do something
}

If the lock is not available at the moment you request it, you may instruct the lock to wait for a given duration using a specified wait interval y using the Block method. If the lock cannot be acquired within the specified time limit, a gocache.ErrBlockWaitTimeout will be raised:

var (
    lock          = cache.Lock("merchant_1", "pid_1", time.Minute)
    acquired, err = lock.Block(time.Second, 30 * time.Second, func() error {
        // do something cool here
    })
)
// handle err
if !acquired {
    // do something
}

Rate Limiter

This package includes a simple to use rate limiter implementation which, in conjunction with a gocache.Cache instance, provides an easy way to limit any set of operations for a predetermined window of time.

The underlying logic of the Rate Limiter implementation allows for a max number of hits x for a given duration y. If x is exceeded during the y timeframe the Rate Limiter will limit further actions until duration y expires. Once duration y is expired the number of hits x will reset back to 0.

Usage

The most basic usage of the Rate Limiter is to throttle a given action. To do so you can call the Throttle method on a Rate Limiter instance as such:

    var (
        // new a RateLimiter instance
        rateLimiter = gocache.NewRateLimiter(cache) // where cache is a gocache.Cache instance
        maxAttempts = 100
        window      = 2 * time.Second
        res, err    = rateLimiter.Throttle("some-key", maxAttempts, window, func() error {
            // Do something here
        })
    )
    // handle err
    // check if request is throttled
    if !res.IsThrottled() {
        // check for remaining attempts
        remaining := res.RemainingAttempts()
        // ...
    } else {
        // check how much you need to wait
        wait := res.RetryAfter()
        // ...
    }    

For more flexible functionality you can call the following methods individually:

    // new a RateLimiter instance
    rateLimiter := gocache.NewRateLimiter(cache) // where cache is a gocache.Cache instance

    // increment the number of hits for a given key for a given time decay
    hits, err := rateLimiter.Hit("some-key", time.Minute)
    // handle err
    
    // get the number of hits for a given key
    hits, err = rateLimiter.Attempts("some-key")
    // handle err
    
    // get the number of hits left
    remaining, err := rateLimiter.AttemptsLeft("some-key")
    // handle err
    
    // check if number of hits has been exceeded
    exceeded, err := rateLimiter.TooManyAttempts("some-key", maxAttempts) // maxAttempts = 100
    // handle err
    
    // reset the number of attempts for a given key
    err = rateLimiter.Clear("some-key")
    // handle err

Contributing

Find an area you can help with and do it. Open source is about collaboration and open participation. Try to make your code look like what already exists or hopefully better and submit a pull request. Also, if you have any ideas on how to make the code better or on improving its scope and functionality please raise an issue and I will do my best to address it in a timely manner.

Liscense

MIT.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound represents an agnostic cache entry not found error
	ErrNotFound = errors.New("gocache: not found")
	// ErrFailedToRetrieveEntry indicates that an entry was not able to be properly retrieved from the cache when
	// calling cache.Many
	ErrFailedToRetrieveEntry = errors.New("gocache: an error occurred while retrieving value, for more detail call Item.Error()")
	// ErrFailedToAddItemEntry is returned when we expected to add an entry to the cache but an entry was already
	// present for the given key
	ErrFailedToAddItemEntry = errors.New("gocache: failed to add entry to cache")
	// ErrBlockWaitTimeout is returned when the max wait for acquiring a lock during a Block call is exceeded
	ErrBlockWaitTimeout = errors.New("gocache: failed to acquire lock due to lock wait timeout")
	// ErrNotImplemented is returned for methods that have not been implemented for the Cache interface
	ErrNotImplemented = errors.New("gocache: method not implemented")
)

Functions

This section is empty.

Types

type Cache

type Cache interface {

	// Lock returns an implementation of the Lock interface
	Lock(name, owner string, duration time.Duration) Lock
	// contains filtered or unexported methods
}

Cache represents the methods a caching store needs to implement

func New

func New(config config, encoder encoder.Encoder) (Cache, error)

New new-ups an instance of Store

type Entry

type Entry struct {
	Key      string
	Value    interface{}
	Duration time.Duration
}

Entry represents a cache entry or input

type Item

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

Item represents a retrieved entry from the cache

func (Item) Bool

func (i Item) Bool() (bool, error)

Bool returns the boolean representation of an Item's value

func (Item) EntryNotFound

func (i Item) EntryNotFound() bool

EntryNotFound checks if an entry was retrieved for the given key

func (Item) Error

func (i Item) Error() error

Error returns the error that occurred when trying to retrieve a given Item

func (Item) Float32

func (i Item) Float32() (float32, error)

Float32 returns the float32 representation of an Item's value

func (Item) Float64

func (i Item) Float64() (float64, error)

Float64 returns the float32 representation of an Item's value

func (Item) Int

func (i Item) Int() (int, error)

Int returns the int representation of an Item's value

func (Item) Int64

func (i Item) Int64() (int64, error)

Int64 returns the int64 representation of an Item's value

func (Item) Key

func (i Item) Key() string

Key returns an Item's key

func (Item) String

func (i Item) String() (string, error)

String returns the string representation of an Item's value

func (Item) TagKey

func (i Item) TagKey() string

TagKey returns the actual key of an Item if it was retrieved with a tag

func (Item) Uint64

func (i Item) Uint64() (uint64, error)

Uint64 returns the uint64 representation of an Item's value

func (Item) Unmarshal

func (i Item) Unmarshal(entity interface{}) error

Unmarshal decodes an Item's value to the provided entity

type Items

type Items map[string]Item

Items is an Item map keyed by the Item key

type LocalConfig

type LocalConfig struct {
	// The value to be appended to every cache entry
	Prefix string
	// DefaultInterval is the interval at which the local store will check for expired keys
	DefaultInterval time.Duration
	// DefaultExpiration is the default local store cache entry expiration time
	DefaultExpiration time.Duration
}

LocalConfig represents the configuration for a cache with a map backend

type LocalStore

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

LocalStore is the representation of a map caching store

func NewLocalStore

func NewLocalStore(cnf *LocalConfig, encoder encoder.Encoder) (*LocalStore, error)

NewLocalStore validates the passed in config and creates a Cache implementation of type *LocalStore

func (*LocalStore) Add added in v1.0.2

func (s *LocalStore) Add(key string, value interface{}, duration time.Duration) (bool, error)

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. If the record was successfully added true will be returned else false will be returned

func (*LocalStore) Close

func (*LocalStore) Close() error

Close closes the c releasing all open resources

func (*LocalStore) Decrement

func (s *LocalStore) Decrement(key string, value int64) (int64, error)

Decrement decrements an integer counter by a given value

func (*LocalStore) Exists added in v1.0.1

func (s *LocalStore) Exists(key string) (bool, error)

Exists checks if an entry exists in the cache for the given key

func (*LocalStore) Expire added in v1.0.6

func (s *LocalStore) Expire(string, time.Duration) error

Expire implementation of the Cache interface

func (*LocalStore) Flush

func (s *LocalStore) Flush() (bool, error)

Flush flushes the store

func (*LocalStore) Forever

func (s *LocalStore) Forever(key string, value interface{}) error

Forever puts a value in the given store until it is forgotten/evicted

func (*LocalStore) Forget

func (s *LocalStore) Forget(key string) (bool, error)

Forget forgets/evicts a given key-value pair from the store

func (*LocalStore) ForgetMany added in v1.0.3

func (s *LocalStore) ForgetMany(keys ...string) error

ForgetMany forgets/evicts a set of given key-value pair from the store

func (*LocalStore) Get

func (s *LocalStore) Get(key string, entity interface{}) error

Get gets the struct representation of a value from the store

func (*LocalStore) GetBool

func (s *LocalStore) GetBool(key string) (bool, error)

GetBool gets a bool value from the store

func (*LocalStore) GetFloat32

func (s *LocalStore) GetFloat32(key string) (float32, error)

GetFloat32 gets a float32 value from the store

func (*LocalStore) GetFloat64

func (s *LocalStore) GetFloat64(key string) (float64, error)

GetFloat64 gets a float value from the store

func (*LocalStore) GetInt

func (s *LocalStore) GetInt(key string) (int, error)

GetInt gets an int value from the store

func (*LocalStore) GetInt64

func (s *LocalStore) GetInt64(key string) (int64, error)

GetInt64 gets an int value from the store

func (*LocalStore) GetString

func (s *LocalStore) GetString(key string) (string, error)

GetString gets a string value from the store

func (*LocalStore) GetUint64

func (s *LocalStore) GetUint64(key string) (uint64, error)

GetUint64 gets an uint64 value from the store

func (*LocalStore) Increment

func (s *LocalStore) Increment(key string, value int64) (int64, error)

Increment increments an integer counter by a given value

func (*LocalStore) Lock

func (s *LocalStore) Lock(name, owner string, duration time.Duration) Lock

Lock returns a map implementation of the Lock interface

func (*LocalStore) Many

func (s *LocalStore) Many(keys ...string) (Items, error)

Many gets many values from the store

func (*LocalStore) Prefix

func (c *LocalStore) Prefix() string

Prefix gets the cache key val

func (*LocalStore) Put

func (s *LocalStore) Put(key string, value interface{}, duration time.Duration) error

Put puts a value in the given store for a predetermined amount of time in seconds.

func (*LocalStore) PutMany

func (s *LocalStore) PutMany(entries ...Entry) error

PutMany puts many values in the given store until they are forgotten/evicted

func (*LocalStore) Tags

func (s *LocalStore) Tags(names ...string) TaggedCache

Tags returns the taggedCache for the given store

type Lock

type Lock interface {

	// Get attempts to acquire a lock. If acquired, fn will be invoked and the lock will be safely release once
	// the invocation either succeeds or errors
	Get(fn func() error) (acquired bool, err error)
	// Block will attempt to acquire a lock for the specified "wait" time. If acquired, fn will be invoked and
	// the lock will be safely release once the invocation either succeeds or errors. The interval variable
	// will be used as the wait duration between attempts to acquire the lock
	Block(interval, wait time.Duration, fn func() error) (acquired bool, err error)
	// contains filtered or unexported methods
}

Lock represents the methods to be implemented by a cache lock

type MemcacheConfig

type MemcacheConfig struct {
	// The value to be appended to every cache entry
	Prefix string
	// Timeout specifies the socket read/write timeout.
	// If zero, DefaultTimeout is used.
	Timeout time.Duration
	// MaxIdleConns specifies the maximum number of idle connections that will
	// be maintained per address. If less than one, DefaultMaxIdleConns will be
	// used.
	//
	// Consider your expected traffic rates and latency carefully. This should
	// be set to a number higher than your peak parallel requests.
	MaxIdleConns int
	// Servers list to be used by the c. Each server is weighted the same
	Servers []string
}

MemcacheConfig represents the configuration for a cache with a Memcache backend

type MemcacheStore

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

MemcacheStore is the representation of the memcache caching store

func NewMemcacheStore

func NewMemcacheStore(cnf *MemcacheConfig, encoder encoder.Encoder) (*MemcacheStore, error)

NewMemcacheStore validates the passed in config and creates a Cache implementation of type *MemcacheStore

func (*MemcacheStore) Add added in v1.0.2

func (s *MemcacheStore) Add(key string, value interface{}, duration time.Duration) (bool, error)

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. If the record was successfully added true will be returned else false will be returned

func (*MemcacheStore) Close

func (*MemcacheStore) Close() error

Close closes the c releasing all open resources

func (*MemcacheStore) Decrement

func (s *MemcacheStore) Decrement(key string, value int64) (int64, error)

Decrement decrements an integer counter by a given value. Please note that for memcache a new value will be capped at 0

func (*MemcacheStore) Exists added in v1.0.1

func (s *MemcacheStore) Exists(key string) (bool, error)

Exists checks if an entry exists in the cache for the given key

func (*MemcacheStore) Expire added in v1.0.6

func (s *MemcacheStore) Expire(key string, duration time.Duration) error

Expire implementation of the Cache interface

func (*MemcacheStore) Flush

func (s *MemcacheStore) Flush() (bool, error)

Flush flushes the store

func (*MemcacheStore) Forever

func (s *MemcacheStore) Forever(key string, value interface{}) error

Forever puts a value in the given store until it is forgotten/evicted

func (*MemcacheStore) Forget

func (s *MemcacheStore) Forget(key string) (bool, error)

Forget forgets/evicts a given key-value pair from the store

func (*MemcacheStore) ForgetMany added in v1.0.3

func (s *MemcacheStore) ForgetMany(keys ...string) error

ForgetMany forgets/evicts a set of given key-value pair from the store

func (*MemcacheStore) Get

func (s *MemcacheStore) Get(key string, entity interface{}) error

Get gets the struct representation of a value from the store

func (*MemcacheStore) GetBool

func (s *MemcacheStore) GetBool(key string) (bool, error)

GetBool gets a bool value from the store

func (*MemcacheStore) GetFloat32

func (s *MemcacheStore) GetFloat32(key string) (float32, error)

GetFloat32 gets a float32 value from the store

func (*MemcacheStore) GetFloat64

func (s *MemcacheStore) GetFloat64(key string) (float64, error)

GetFloat64 gets a float64 value from the store

func (*MemcacheStore) GetInt

func (s *MemcacheStore) GetInt(key string) (int, error)

GetInt gets an int value from the store

func (*MemcacheStore) GetInt64

func (s *MemcacheStore) GetInt64(key string) (int64, error)

GetInt64 gets an int64 value from the store

func (*MemcacheStore) GetString

func (s *MemcacheStore) GetString(key string) (string, error)

GetString gets a string value from the store

func (*MemcacheStore) GetUint64

func (s *MemcacheStore) GetUint64(key string) (uint64, error)

GetUint64 gets an uint64 value from the store

func (*MemcacheStore) Increment

func (s *MemcacheStore) Increment(key string, value int64) (int64, error)

Increment increments an integer counter by a given value

func (*MemcacheStore) Lock

func (s *MemcacheStore) Lock(name, owner string, duration time.Duration) Lock

Lock returns a memcache implementation of the Lock interface

func (*MemcacheStore) Many

func (s *MemcacheStore) Many(keys ...string) (Items, error)

Many gets many values from the store

func (*MemcacheStore) Prefix

func (c *MemcacheStore) Prefix() string

Prefix gets the cache key val

func (*MemcacheStore) Put

func (s *MemcacheStore) Put(key string, value interface{}, duration time.Duration) error

Put puts a value in the given store for a predetermined amount of time in seconds

func (*MemcacheStore) PutMany

func (s *MemcacheStore) PutMany(entries ...Entry) error

PutMany puts many values in the given store until they are forgotten/evicted

func (*MemcacheStore) Tags

func (s *MemcacheStore) Tags(names ...string) TaggedCache

Tags returns the taggedCache for the given store

type RateLimiter added in v1.0.4

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

RateLimiter is a struct whose purpose is to limit the rate at which something is executed or accessed. The underlying logic of this implementation allows for a max number of hits x for a given duration y. If x is exceeded during the y timeframe the RateLimiter will limit further calls until duration y expires. Once duration y is expired calls will reset back to 0

func NewRateLimiter added in v1.0.4

func NewRateLimiter(cache Cache) *RateLimiter

NewRateLimiter creates an instance of *RateLimiter

func (*RateLimiter) Attempts added in v1.0.4

func (l *RateLimiter) Attempts(key string) (int64, error)

Attempts gets the number of attempts for the given key

func (*RateLimiter) AttemptsLeft added in v1.0.4

func (l *RateLimiter) AttemptsLeft(key string, maxAttempts int64) (int64, error)

AttemptsLeft gets the number of attempts left for a given key

func (*RateLimiter) AvailableIn added in v1.0.4

func (l *RateLimiter) AvailableIn(key string) (time.Duration, error)

AvailableIn gets the number of seconds until the "key" is accessible again

func (*RateLimiter) Clear added in v1.0.4

func (l *RateLimiter) Clear(key string) error

Clear clears the hits and lockout timer for the given key

func (*RateLimiter) Hit added in v1.0.4

func (l *RateLimiter) Hit(key string, decay time.Duration) (hits int64, err error)

Hit increments the counter for a given key for a given decay time

func (*RateLimiter) Throttle added in v1.0.4

func (l *RateLimiter) Throttle(key string, maxCalls int64, decay time.Duration, fn func() error) (*ThrottleResponse, error)

Throttle rate limits the calls that made to fn

func (*RateLimiter) TooManyAttempts added in v1.0.4

func (l *RateLimiter) TooManyAttempts(key string, maxAttempts int64) (bool, error)

TooManyAttempts determines if the given key has been "accessed" too many times

type RedisConfig

type RedisConfig struct {
	// The value to be appended to every cache entry
	Prefix string
	// The network type, either tcp or unix.
	// Default is tcp.
	Network string
	// host:port address.
	Addr string
	// Dialer creates new network connection and has priority over
	// Network and Addr options.
	Dialer func() (net.Conn, error)
	// Hook that is called when new connection is established.
	OnConnect func(*redis.Conn) error
	// Optional password. Must match the password specified in the
	// requirepass server configuration option.
	Password string
	// Database to be selected after connecting to the server.
	DB int
	// Maximum number of retries before giving up.
	// Default is to not retry failed commands.
	MaxRetries int
	// Minimum backoff between each retry.
	// Default is 8 milliseconds; -1 disables backoff.
	MinRetryBackoff time.Duration
	// Maximum backoff between each retry.
	// Default is 512 milliseconds; -1 disables backoff.
	MaxRetryBackoff time.Duration
	// Dial timeout for establishing new connections.
	// Default is 5 seconds.
	DialTimeout time.Duration
	// Timeout for socket reads. If reached, commands will fail
	// with a timeout instead of blocking. Use value -1 for no timeout and 0 for default.
	// Default is 3 seconds.
	ReadTimeout time.Duration
	// Timeout for socket writes. If reached, commands will fail
	// with a timeout instead of blocking.
	// Default is ReadTimeout.
	WriteTimeout time.Duration
	// Maximum number of socket connections.
	// Default is 10 connections per every CPU as reported by runtime.NumCPU.
	PoolSize int
	// Minimum number of idle connections which is useful when establishing
	// new connection is slow.
	MinIdleConns int
	// Connection age at which c retires (closes) the connection.
	// Default is to not close aged connections.
	MaxConnAge time.Duration
	// Amount of time c waits for connection if all connections
	// are busy before returning an error.
	// Default is ReadTimeout + 1 second.
	PoolTimeout time.Duration
	// Amount of time after which c closes idle connections.
	// Should be less than server's timeout.
	// Default is 5 minutes. -1 disables idle timeout check.
	IdleTimeout time.Duration
	// Frequency of idle checks made by idle connections reaper.
	// Default is 1 minute. -1 disables idle connections reaper,
	// but idle connections are still discarded by the c
	// if IdleTimeout is set.
	IdleCheckFrequency time.Duration
	// TLS Config to use. When set TLS will be negotiated.
	TLSConfig *tls.Config
}

RedisConfig represents the configuration for a cache with a redis backend

type RedisStore

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

RedisStore is the representation of the redis caching store

func NewRedisStore

func NewRedisStore(cnf *RedisConfig, encoder encoder.Encoder) (*RedisStore, error)

NewRedisStore validates the passed in config and creates a Cache implementation of type *RedisStore

func (*RedisStore) Add added in v1.0.2

func (s *RedisStore) Add(key string, value interface{}, duration time.Duration) (bool, error)

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. If the record was successfully added true will be returned else false will be returned

func (*RedisStore) Close

func (s *RedisStore) Close() error

Close closes the c releasing all open resources

func (*RedisStore) Decrement

func (s *RedisStore) Decrement(key string, value int64) (int64, error)

Decrement decrements an integer counter by a given value

func (*RedisStore) Exists added in v1.0.1

func (s *RedisStore) Exists(key string) (bool, error)

Exists checks if an entry exists in the cache for the given key

func (*RedisStore) Expire added in v1.0.6

func (s *RedisStore) Expire(key string, duration time.Duration) error

Expire implementation of the Cache interface

func (*RedisStore) Flush

func (s *RedisStore) Flush() (bool, error)

Flush flushes the store

func (*RedisStore) Forever

func (s *RedisStore) Forever(key string, value interface{}) error

Forever puts a value in the given store until it is forgotten/evicted

func (*RedisStore) Forget

func (s *RedisStore) Forget(key string) (bool, error)

Forget forgets/evicts a given key-value pair from the store

func (*RedisStore) ForgetMany added in v1.0.3

func (s *RedisStore) ForgetMany(keys ...string) error

ForgetMany forgets/evicts a set of given key-value pair from the store

func (*RedisStore) Get

func (s *RedisStore) Get(key string, entity interface{}) error

Get gets the struct representation of a value from the store

func (*RedisStore) GetBool

func (s *RedisStore) GetBool(key string) (bool, error)

GetBool gets a bool value from the store

func (*RedisStore) GetFloat32

func (s *RedisStore) GetFloat32(key string) (float32, error)

GetFloat32 gets a float32 value from the store

func (*RedisStore) GetFloat64

func (s *RedisStore) GetFloat64(key string) (float64, error)

GetFloat64 gets a float64 value from the store

func (*RedisStore) GetInt

func (s *RedisStore) GetInt(key string) (int, error)

GetInt gets an int value from the store

func (*RedisStore) GetInt64

func (s *RedisStore) GetInt64(key string) (int64, error)

GetInt64 gets an int64 value from the store

func (*RedisStore) GetString

func (s *RedisStore) GetString(key string) (string, error)

GetString gets a string value from the store

func (*RedisStore) GetUint64

func (s *RedisStore) GetUint64(key string) (uint64, error)

GetUint64 gets an uint64 value from the store

func (*RedisStore) Increment

func (s *RedisStore) Increment(key string, value int64) (int64, error)

Increment increments an integer counter by a given value

func (*RedisStore) Lock

func (s *RedisStore) Lock(name, owner string, duration time.Duration) Lock

Lock returns a redis implementation of the Lock interface

func (*RedisStore) Lpush

func (s *RedisStore) Lpush(segment, key string) error

Lpush runs the Redis lpush command (used via reflection, do not delete)

func (*RedisStore) Lrange

func (s *RedisStore) Lrange(key string, start, stop int64) []string

Lrange runs the Redis lrange command (used via reflection, do not delete)

func (*RedisStore) Many

func (s *RedisStore) Many(keys ...string) (Items, error)

Many gets many values from the store

func (*RedisStore) Prefix

func (c *RedisStore) Prefix() string

Prefix gets the cache key val

func (*RedisStore) Put

func (s *RedisStore) Put(key string, value interface{}, duration time.Duration) error

Put puts a value in the given store for a predetermined amount of time in seconds

func (*RedisStore) PutMany

func (s *RedisStore) PutMany(entries ...Entry) error

PutMany puts many values in the given store until they are forgotten/evicted

func (*RedisStore) Tags

func (s *RedisStore) Tags(names ...string) TaggedCache

Tags returns the taggedCache for the given store

type TagSet added in v1.0.3

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

TagSet is the representation of a set of tags to be used to interact with the caching stores

func (*TagSet) Flush added in v1.0.3

func (ts *TagSet) Flush() error

Flush clears removes all tags associated with the TagSet from the cache

func (*TagSet) Names added in v1.0.3

func (ts *TagSet) Names() []string

func (*TagSet) Reset added in v1.0.3

func (ts *TagSet) Reset() error

Reset will reinitialize the value of all tags in the TagSet

func (*TagSet) TagIds added in v1.0.3

func (ts *TagSet) TagIds() ([]string, error)

TagIds returns all the ids associated to the TagSet tags

type TaggedCache

type TaggedCache interface {

	// TagSet returns the underlying tagged cache tag set
	TagSet() *TagSet
	// contains filtered or unexported methods
}

TaggedCache represents the methods a tagged-caching store needs to implement

type ThrottleResponse added in v1.0.4

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

ThrottleResponse contains relevant information with respect to calls that are meant to be rate limited

func (*ThrottleResponse) IsThrottled added in v1.0.4

func (r *ThrottleResponse) IsThrottled() bool

IsThrottled returns if the number of calls have been throttled

func (*ThrottleResponse) MaxAttempts added in v1.0.4

func (r *ThrottleResponse) MaxAttempts() int64

MaxAttempts returns the max attempts for a given call

func (*ThrottleResponse) RemainingAttempts added in v1.0.4

func (r *ThrottleResponse) RemainingAttempts() int64

RemainingAttempts returns the remaining calls that can be made to a function before it is throttled

func (*ThrottleResponse) RetryAfter added in v1.0.4

func (r *ThrottleResponse) RetryAfter() time.Duration

RetryAfter returns the duration that one should wait before executing the next call

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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