cache

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2024 License: Apache-2.0 Imports: 8 Imported by: 4

README

Cache

Go Reference Release Go Report Card codecov Test GitHub issues License

The Cache package provides a unified interface for managing caches in Go. It allows developers to switch between various cache implementations (such as Redis, Memcache, etc.) by simply altering the URL scheme.

Installation

go get -u github.com/bartventer/gocache

Supported Cache Implementations

Name Author Docs
Redis go-redis/redis Go Reference
Redis Cluster go-redis/redis Go Reference
Memcache bradfitz/gomemcache Go Reference
RAM Cache (in-memory) bartventer/gocache Go Reference

Pull requests for additional cache implementations are welcome!

Usage

To use a cache implementation, import the relevant driver package and use the OpenCache function to create a new cache. The cache package will automatically use the correct cache implementation based on the URL scheme.

Redis

The redis package provides a Redis cache implementation using the go-redis/redis client.

import (
    "context"
    "log"

    cache "github.com/bartventer/gocache"
    _ "github.com/bartventer/gocache/redis"
)

func main() {
    ctx := context.Background()
    urlStr := "redis://localhost:7000?maxretries=5&minretrybackoff=1000ms"
    c, err := cache.OpenCache(ctx, urlStr, cache.Options{})
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }
    // ... use c with the cache.Cache interface
}
Redis Constructor
import (
    "context"

    "github.com/bartventer/gocache"
    "github.com/bartventer/gocache/redis"
    "github.com/redis/go-redis/v9"
)

func main() {
    ctx := context.Background()
    c := redis.New(ctx, cache.Config{}, redis.Options{
        Addr: "localhost:7000",
    })
    // ... use c with the cache.Cache interface
}
Redis Cluster

The rediscluster package provides a Redis Cluster cache implementation using the go-redis/redis client.

import (
    "context"
    "log"

    cache "github.com/bartventer/gocache"
    _ "github.com/bartventer/gocache/rediscluster"
)

func main() {
    ctx := context.Background()
    urlStr := "rediscluster://localhost:7000,localhost:7001,localhost:7002?maxretries=5&minretrybackoff=1000"
    c, err := cache.OpenCache(ctx, urlStr, cache.Options{})
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }
    // ... use c with the cache.Cache interface
}
Redis Cluster Constructor
import (
    "context"

    "github.com/bartventer/gocache"
    "github.com/bartventer/gocache/rediscluster"
    "github.com/redis/go-redis/v9"
)

func main() {
    ctx := context.Background()
    c := rediscluster.New(ctx, cache.Config{}, redis.ClusterOptions{
        Addrs: []string{"localhost:7000", "localhost:7001", "localhost:7002"},
    })
    // ... use c with the cache.Cache interface
}
Memcache

The memcache package provides a Memcache cache implementation using the bradfitz/gomemcache client.

import (
    "context"
    "log"

    cache "github.com/bartventer/gocache"
    _ "github.com/bartventer/gocache/memcache"
)

func main() {
    ctx := context.Background()
    urlStr := "memcache://localhost:11211"
    c, err := cache.OpenCache(ctx, urlStr, cache.Options{})
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }
    // ... use c with the cache.Cache interface
}
Memcache Constructor
import (
    "context"

    "github.com/bartventer/gocache"
    "github.com/bartventer/gocache/memcache"
)

func main() {
    ctx := context.Background()
    c := memcache.New(ctx, cache.Config{}, "localhost:11211")
    // ... use c with the cache.Cache interface
}
RAM Cache (in-memory)

The ramcache package provides an in-memory cache implementation using a map.

import (
    "context"
    "log"

    cache "github.com/bartventer/gocache"
    _ "github.com/bartventer/gocache/ramcache"
)

func main() {
    ctx := context.Background()
    c, err := cache.OpenCache(ctx, "ramcache://?defaultttl=5m", cache.Options{})
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }
    // ... use c with the cache.Cache interface
}
RAM Cache Constructor
import (
    "context"

    "github.com/bartventer/gocache"
    "github.com/bartventer/gocache/ramcache"
)

func main() {
    ctx := context.Background()
    c := ramcache.New(ctx, &cache.Config{}, ramcache.Options{DefaultTTL: 5 * time.Minute})
    // ... use c with the cache.Cache interface
}

Contributing

All contributions are welcome! Open a pull request to request a feature or submit a bug report.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Documentation

Overview

Package cache offers a library for managing caches in a unified manner in Go.

This package enables developers to transition between various cache implementations (such as Redis, Redis Cluster, etc.) by altering the URL scheme. This is achieved by offering consistent, idiomatic interfaces for common operations.

Central to this package are "portable types", built atop service-specific drivers for supported cache services. For instance, cache.Cache portable type instances can be created using redis.OpenCache, memcache.OpenCache, or any other supported driver. This allows the cache.Cache to be used across your application without concern for the underlying implementation.

URL Format

The cache package uses URLs to specify cache implementations. The URL scheme is used to determine the cache implementation to use. The URL format is:

scheme://<host>:<port>[?query]

The scheme is used to determine the cache implementation. The host and port are used to connect to the cache service. The optional query parameters can be used to configure the cache implementation. Each cache implementation supports different query parameters. Refer to the documentation of each cache implementation for more information.

Usage

To use a cache implementation, import the relevant driver package and use the OpenCache function to create a new cache. The cache package will automatically use the correct cache implementation based on the URL scheme.

import (
    "context"
    "log"

    "github.com/bartventer/gocache"
    // Enable the Redis cache implementation
    _ "github.com/bartventer/gocache/redis"
)

func main() {
    ctx := context.Background()
    urlStr := "redis://localhost:7000?maxretries=5&minretrybackoff=1000"
    c, err := cache.OpenCache(ctx, urlStr, cache.Options{})
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }

    // Now you can use c with the cache.Cache interface
    err = c.Set(ctx, "key", "value")
    if err != nil {
        log.Fatalf("Failed to set key: %v", err)
    }

    value, err := c.Get(ctx, "key")
    if err != nil {
        log.Fatalf("Failed to get key: %v", err)
    }

    log.Printf("Value: %s", value)
}

Drivers

For specific URL formats, query parameters, and examples, refer to the documentation of each cache implementation.

Index

Constants

View Source
const (
	// DefaultCountLimit is the default value for the [Config.CountLimit] option.
	DefaultCountLimit = 10
)

Variables

View Source
var (
	// ErrNoCache is returned when no cache implementation is available.
	ErrNoCache = errors.New("gocache: no cache implementation available")

	// ErrKeyNotFound is returned when a key is not found in the cache.
	ErrKeyNotFound = errors.New("gocache: key not found")

	// ErrPatternMatchingNotSupported is returned when a pattern matching operation is not supported
	// by the cache implementation.
	ErrPatternMatchingNotSupported = errors.New("gocache: pattern matching not supported")
)

Functions

func RegisterCache

func RegisterCache(scheme string, opener URLOpener)

RegisterCache registers a URLOpener for a given scheme. If a URLOpener is already registered for the scheme, it panics.

Types

type Cache

type Cache interface {
	// Set sets a key to a value in the cache.
	Set(ctx context.Context, key string, value interface{}, modifiers ...keymod.KeyModifier) error

	// SetWithExpiry sets a key to a value in the cache with an expiry time.
	SetWithExpiry(ctx context.Context, key string, value interface{}, expiry time.Duration, modifiers ...keymod.KeyModifier) error

	// Exists checks if a key exists in the cache.
	Exists(ctx context.Context, key string, modifiers ...keymod.KeyModifier) (bool, error)

	// Count returns the number of keys in the cache matching a pattern.
	Count(ctx context.Context, pattern string, modifiers ...keymod.KeyModifier) (int64, error)

	// Get gets the value of a key from the cache.
	Get(ctx context.Context, key string, modifiers ...keymod.KeyModifier) ([]byte, error)

	// Del deletes a key from the cache.
	Del(ctx context.Context, key string, modifiers ...keymod.KeyModifier) error

	// DelKeys deletes all keys matching a pattern from the cache.
	DelKeys(ctx context.Context, pattern string, modifiers ...keymod.KeyModifier) error

	// Clear clears all keys from the cache.
	Clear(ctx context.Context) error

	// Ping checks if the cache is available.
	Ping(ctx context.Context) error

	// Close closes the cache connection.
	Close() error
}

Cache is an interface that represents a cache. It has methods for setting, getting and deleting keys. Each cache implementation should implement this interface.

func OpenCache

func OpenCache(ctx context.Context, urlstr string, options *Options) (Cache, error)

OpenCache opens a Cache using a URL string and options. It returns an error if the URL cannot be parsed, or if no URLOpener is registered for the URL's scheme.

type Config

type Config struct {

	// CountLimit is the hint to the SCAN command about the amount of work to be done at each call.
	// It does not guarantee the exact number of elements returned at every iteration, but the server
	// will usually return this count or a few more elements per call. For small sets or hashes, all
	// elements may be returned in the first SCAN call regardless of the CountLimit value. The CountLimit
	// value can be changed between iterations. The default value is 10.
	CountLimit int64
	// contains filtered or unexported fields
}

Config is a struct that holds configuration options for the cache package.

Compatibility

These options are recognized by all cache drivers.

func (*Config) Revise

func (c *Config) Revise()

Revise revises the configuration options to ensure they contain sensible values.

type Options

type Options struct {
	Config
	// TLSConfig is the TLS configuration for the cache connection.
	TLSConfig *tls.Config
	// CredentialsProvider is a function that returns the username and password for the cache connection.
	CredentialsProvider func(ctx context.Context) (username string, password string, err error)
	// Metadata is a map of provider specific configuration options.
	// It offers an alternative method for configuring the provider.
	// These values will override the URL values.
	// Note: Network address (host:port) and function values will be ignored if provided.
	// Refer to the driver documentation for available options.
	// The map keys are case insensitive.
	//
	// Example usage for a Redis cache:
	//
	//  map[string]string{
	// 	 	"Network": "tcp",
	// 	 	"MaxRetries": "3",
	// 	 	"MinRetryBackoff": "8ms",
	// 	 	"PoolFIFO": "true",
	// 	}
	//
	// This is equivalent to providing query parameters in the URL:
	//
	// 	redis://localhost:6379?network=tcp&maxretries=3&minretrybackoff=8ms&poolfifo=true
	Metadata map[string]string
}

Options is a struct that holds provider specific configuration options.

Compatibility

These options are only recognized by the following drivers:

Other drivers will simply ignore these options.

type URLOpener

type URLOpener interface {
	// OpenCacheURL opens a cache using a URL and options.
	OpenCacheURL(ctx context.Context, u *url.URL, options *Options) (Cache, error)
}

URLOpener is an interface for opening caches using URLs.

Directories

Path Synopsis
Package drivertest provides conformance tests for cache implementations.
Package drivertest provides conformance tests for cache implementations.
internal
gcerrors
Package gcerrors provides error handling for the gocache package.
Package gcerrors provides error handling for the gocache package.
Package keymod provides functions for modifying keys.
Package keymod provides functions for modifying keys.
memcache module
ramcache module
redis module
rediscluster module

Jump to

Keyboard shortcuts

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