stash

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2021 License: MIT Imports: 11 Imported by: 1

README

Stash

A cross driver cache store (stash) for Redis, MemCached & In-Memory storage. Stash is a wrapper for GoCache with automatic marshaling and unmarshalling of cache items.

made-with-Go Test codecov GoReportCard GoDoc

Built-in stores

Install

go get github.com/lacuna-seo/stash

Provider

A provider can is an interface that can be used to pass to stash.Load. It is used as a driver for common methods between each memory store (Memory, Redis ot Memcache).

It is the result of what is called by NewMemory, NewRedis or NewMemcache. Which can be pinged. and validated. The methods are described below.

type Provider interface {
    // Ping the store.
    Ping() error
    
    // Validate checks the environment for errors.
    Validate() error
    
    // Driver returns the store's name.
    Driver() string
    
    // Store returns the interface for use within
    // the cache.
    Store() store.StoreInterface
}

Store

A store is what is used to interact with the cache driver. Items can retrieve, set, deleted, invalidated and flushed. The methods are described below.

type Store interface {
    // Get retrieves a specific item from the cache by key. Values are
    // automatically marshalled for use with Redis & Memcache.
    Get(ctx context.Context, key, v interface{}) error
    
    // Set stores a singular item in memory by key, value
    // and options (tags and expiration time). Values are automatically
    // marshalled for use with Redis & Memcache.
    Set(ctx context.Context, key interface{}, value interface{}, options Options) error
    
    // Delete removes a singular item from the cache by
    // a specific key.
    Delete(ctx context.Context, key interface{}) error
    
    // Invalidate removes items from the cache via the
    // InvalidateOptions passed.
    Invalidate(ctx context.Context, options InvalidateOptions) error
    
    // Clear removes all items from the cache.
    Clear(ctx context.Context) error
}

Memory (go-cache)

To create a new Memory (go-cache) store call stash.NewMemory and pass in a default expiry and default clean up duration.

➡️ Click here for an example.

provider := stash.NewMemory(5*time.Minute, 10*time.Minute)

cache, err := stash.Load(provider)
if err != nil {
    log.Fatalln(err)
}

err = cache.Set(context.Background(), "key", []byte("stash"), stash.Options{
    Expiration: time.Hour * 1,
})
if err != nil {
    log.Fatalln(err)
}

var buf []byte
err = cache.Get(context.Background(), "key", &buf)
if err != nil {
    log.Fatalln(err)
}

fmt.Println(string(buf)) // Returns stash

Redis

To create a new Redis store call stash.NewRedis and pass in the redis options from github.com/go-redis/redis/v8 (ensure that it is imported) and a default expiry.

➡️ Click here for an example.

provider := stash.NewRedis(redis.Options{
    Addr: "127.0.0.1:6379",
}, 5*time.Minute)

cache, err := stash.Load(provider)
if err != nil {
    log.Fatalln(err)
}

err = cache.Set(context.Background(), "key", []byte("stash"), stash.Options{
    Expiration: time.Hour * 1,
})
if err != nil {
    log.Fatalln(err)
}

var buf []byte
err = cache.Get(context.Background(), "key", &buf)
if err != nil {
    log.Fatalln(err)
}

fmt.Println(string(buf)) // Returns stash

Memcache

To create a new Memcache store call stash.NewMemcache and pass a slice of strings that correlate to a memcache server and a default expiry.

➡️ Click here for an example.

provider := stash.NewMemcache([]string{"127.0.0.1:11211"}, 5*time.Minute)

cache, err := stash.Load(provider)
if err != nil {
    log.Fatalln(err)
}

err = cache.Set(context.Background(), "key", []byte("stash"), stash.Options{
    Expiration: time.Hour * 1,
})
if err != nil {
    log.Fatalln(err)
}

var buf []byte
err = cache.Get(context.Background(), "key", &buf)
if err != nil {
    log.Fatalln(err)
}

fmt.Println(string(buf)) // Returns stash

Tags

Cache invalidaton is hard. By using tags you are able to group cache items together and invalidate them by a slice of strings.

// Set a cache key with the value of 'stash' and a tag of 'category`.
// The cache item will be expired after one hour.
err := cache.Set(context.Background(), "key", []byte("stash"), stash.Options{
    Expiration: time.Hour * 1,
    Tags:       []string{"category"},
})
if err != nil {
    log.Fatalln(err)
}

// Invalidate all cache items that have a tag called 'category' 
// associated with them.
err = cache.Invalidate(context.Background(), stash.InvalidateOptions{
    Tags: []string{"category"},
})
if err != nil {
    log.Fatalln(err)
}

Examples

To run the examples, clone the repo and run make setup and choose one of the following commands to run an example with a particular store.

Memory: make memory:example

Redis: make redis:example

Memcache: make memcache:example

Credits

Thanks to https://github.com/eko/gocache

Documentation

Index

Constants

View Source
const (
	// MemoryDriver is the Redis Driver, depicted
	// in the environment.
	MemoryDriver = "memory"
	// RedisDriver is the Redis Driver, depicted
	// in the environment.
	RedisDriver = "redis"
	// MemcacheDriver is the Memcached Driver, depicted
	// in the environment.
	MemcacheDriver = "memcache"
	// RememberForever is an alias for setting the
	// cache item to never be removed.
	RememberForever = -1
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {

	// Driver is the current store being used, it can be
	// MemoryDriver, RedisDriver or MemcachedDriver.
	Driver string
	// contains filtered or unexported fields
}

Cache defines the methods for interacting with the cache layer.

func Load

func Load(prov Provider) (*Cache, error)

Load initialises the cache store by the environment. It will load a Driver into memory ready for setting getting setting and deleting. Drivers supported are Memory Redis and MemCached. Returns ErrInvalidDriver if the Driver passed does not exist.

func (*Cache) Clear

func (c *Cache) Clear(ctx context.Context) error

Clear removes all items from the cache.

func (*Cache) Delete

func (c *Cache) Delete(ctx context.Context, key interface{}) error

Delete removes a singular item from the cache by a specific key.

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, key, v interface{}) error

Get retrieves a specific item from the cache by key. Values are automatically marshalled for use with Redis & Memcache.

func (*Cache) Invalidate

func (c *Cache) Invalidate(ctx context.Context, options InvalidateOptions) error

Invalidate removes items from the cache via the InvalidateOptions passed.

func (*Cache) Set

func (c *Cache) Set(ctx context.Context, key interface{}, value interface{}, options Options) error

Set stores a singular item in memory by key, value and options (tags and expiration time). Values are automatically marshalled for use with Redis & Memcache.

type InvalidateOptions

type InvalidateOptions struct {
	// Tags allows to specify associated tags to the
	// current value.
	Tags []string
}

InvalidateOptions represents the options for invalidating the cache.

type Options

type Options struct {
	// Expiration allows to specify a global expiration
	// time hen setting a value.
	Expiration time.Duration
	// Tags allows specifying associated tags to the
	// current value.
	Tags []string
}

Options represents the cache store available options when using Set().

type Provider

type Provider interface {
	// Ping the store.
	Ping() error

	// Validate checks the environment for errors.
	Validate() error

	// Driver returns the store's name.
	Driver() string

	// Store returns the interface for use within
	// the cache.
	Store() store.StoreInterface
}

Provider defines the methods for a cache Provider.

func NewMemcache

func NewMemcache(servers []string, defaultExpiration time.Duration) Provider

NewMemcache creates a new memcached store and returns a provider.

func NewMemory

func NewMemory(defaultExpiration, cleanupInterval time.Duration) Provider

NewMemory creates a new go-cache store and returns a provider.

func NewRedis

func NewRedis(options redis.Options, defaultExpiration time.Duration) Provider

NewRedis creates a new redis store and returns a provider.

type Store

type Store interface {
	// Get retrieves a specific item from the cache by key. Values are
	// automatically marshalled for use with Redis & Memcache.
	Get(ctx context.Context, key, v interface{}) error

	// Set stores a singular item in memory by key, value
	// and options (tags and expiration time). Values are automatically
	// marshalled for use with Redis & Memcache.
	Set(ctx context.Context, key interface{}, value interface{}, options Options) error

	// Delete removes a singular item from the cache by
	// a specific key.
	Delete(ctx context.Context, key interface{}) error

	// Invalidate removes items from the cache via the
	// InvalidateOptions passed.
	Invalidate(ctx context.Context, options InvalidateOptions) error

	// Clear removes all items from the cache.
	Clear(ctx context.Context) error
}

Store defines methods for interacting with the caching system.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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