cache

package module
v1.15.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2024 License: Apache-2.0 Imports: 9 Imported by: 4

README

Cache

Go Reference Release Go Report Card codecov Test GitHub issues License

The Cache package in Go provides a unified, portable API for managing caches, enabling developers to write cache-related code once and transition seamlessly between different cache drivers with minimal reconfiguration. This approach simplifies both local testing and deployment to different environments.

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

Note: More coming soon!

See the Contributing section if you would like to add a new cache implementation.

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 driver based on the URL scheme. Each driver also provides a constructor function for manual initialization.

Redis

The redis package provides a Redis cache driver 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=1s"
    c, err := cache.OpenCache(ctx, urlStr)
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }
    // ... use c with the cache.Cache interface
}
Redis Constructor

You can create a Redis cache with redis.New:

import (
    "context"

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

func main() {
    ctx := context.Background()
    c := redis.New[string](ctx, &redis.Options{
        RedisOptions: &redis.RedisOptions{
            Addr: "localhost:7000",
            MaxRetries: 5,
            MinRetryBackoff: 1 * time.Second,
        },
    })
    // ... use c with the cache.Cache interface
}
Redis Cluster

The rediscluster package provides a Redis Cluster cache driver 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=1s"
    c, err := cache.OpenCache(ctx, urlStr)
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }
    // ... use c with the cache.Cache interface
}
Redis Cluster Constructor

You can create a Redis Cluster cache with rediscluster.New:

import (
    "context"

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

func main() {
    ctx := context.Background()
    c := rediscluster.New[string](ctx, &rediscluster.Options{
        ClusterOptions: &rediscluster.ClusterOptions{
            Addrs: []string{"localhost:7000", "localhost:7001", "localhost:7002"},
            MaxRetries: 5,
            MinRetryBackoff: 1 * time.Second,
        },
    })
    // ... use c with the cache.Cache interface
}
Memcache

The memcache package provides a Memcache cache driver 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)
    if err != nil {
        log.Fatalf("Failed to initialize cache: %v", err)
    }
    // ... use c with the cache.Cache interface
}
Memcache Constructor

You can create a Memcache cache with memcache.New:

import (
    "context"

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

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

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

import (
    "context"
    "log"

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

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

You can create a RAM cache with ramcache.New:

import (
    "context"

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

func main() {
    ctx := context.Background()
    c := ramcache.New[string](ctx, &ramcache.Options{
        CleanupInterval: 1 * time.Minute,
    })
    // ... use c with the cache.Cache interface
}

Contributing

All contributions are welcome! See the Contributing Guide for more details.

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, Memcache, 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, the GenericCache type is a portable type that implements the driver.Cache interface. This allows developers to use the same code with different cache implementations.

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.

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[string](ctx, urlStr)
    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.

Custom Key Types

The cache package supports any string-like type for keys. Custom key types can be used by registering it alongside the cache implementation with RegisterCache. This allows the cache package to automatically convert the custom key type to a string when interacting with the cache.

The following key types are supported by default:

For an example of how to register a custom key type, refer to the redis driver package.

Index

Constants

This section is empty.

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")

	// ErrInvalidTTL is returned when an invalid TTL is provided.
	ErrInvalidTTL = errors.New("gocache: invalid TTL")
)

Functions

func RegisterCache

func RegisterCache[K driver.String](scheme string, opener URLOpener[K])

RegisterCache registers a URLOpener for a given scheme and type. If a URLOpener is already registered for the scheme and type, it panics. Not intended for direct application use.

func ValidateTTL added in v0.10.0

func ValidateTTL(ttl time.Duration) error

ValidateTTL validates the TTL and returns an error if it's invalid. A TTL is invalid if it's negative.

Types

type Cache

type Cache = GenericCache[string]

Cache is a type alias for GenericCache with string keys.

func OpenCache

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

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

type GenericCache added in v0.15.0

type GenericCache[K driver.String] struct {
	// contains filtered or unexported fields
}

GenericCache is a portable type that implements driver.Cache.

func NewCache added in v0.14.0

func NewCache[K driver.String](driver driver.Cache[K]) *GenericCache[K]

NewCache creates a new GenericCache using the provided driver. Not intended for direct application use.

func OpenGenericCache added in v0.15.0

func OpenGenericCache[K driver.String](ctx context.Context, urlstr string) (*GenericCache[K], error)

OpenGenericCache opens a GenericCache for the provided URL string and type. It returns an error if the URL cannot be parsed, or if no URLOpener is registered for the URL's scheme and type. Not intended for direct application use.

func (*GenericCache[K]) Clear added in v0.15.0

func (c *GenericCache[K]) Clear(ctx context.Context) error

Clear implements driver.Cache.

func (*GenericCache[K]) Close added in v0.15.0

func (c *GenericCache[K]) Close() error

Close implements driver.Cache.

func (*GenericCache[K]) Count added in v0.15.0

func (c *GenericCache[K]) Count(ctx context.Context, pattern K) (int64, error)

Count implements driver.Cache.

func (*GenericCache[K]) Del added in v0.15.0

func (c *GenericCache[K]) Del(ctx context.Context, key K) error

Del implements driver.Cache.

func (*GenericCache[K]) DelKeys added in v0.15.0

func (c *GenericCache[K]) DelKeys(ctx context.Context, pattern K) error

DelKeys implements driver.Cache.

func (*GenericCache[K]) Exists added in v0.15.0

func (c *GenericCache[K]) Exists(ctx context.Context, key K) (bool, error)

Exists implements driver.Cache.

func (*GenericCache[K]) Get added in v0.15.0

func (c *GenericCache[K]) Get(ctx context.Context, key K) ([]byte, error)

Get implements driver.Cache.

func (*GenericCache[K]) Ping added in v0.15.0

func (c *GenericCache[K]) Ping(ctx context.Context) error

Ping implements driver.Cache.

func (*GenericCache[K]) Set added in v0.15.0

func (c *GenericCache[K]) Set(ctx context.Context, key K, value interface{}) error

Set implements driver.Cache.

func (*GenericCache[K]) SetWithTTL added in v0.15.0

func (c *GenericCache[K]) SetWithTTL(ctx context.Context, key K, value interface{}, ttl time.Duration) error

SetWithTTL implements driver.Cache.

type KeyCache added in v0.15.0

type KeyCache = GenericCache[keymod.Key]

KeyCache is a type alias for GenericCache with keymod.Key keys.

func OpenKeyCache added in v0.15.0

func OpenKeyCache(ctx context.Context, urlstr string) (*KeyCache, error)

OpenKeyCache opens a KeyCache for the provided URL string. It returns an error if the URL cannot be parsed, or if no URLOpener is registered for the URL's scheme.

type URLOpener

type URLOpener[K driver.String] interface {
	// OpenCacheURL opens a cache using a URL and options.
	OpenCacheURL(ctx context.Context, u *url.URL) (*GenericCache[K], error)
}

URLOpener defines the interface for opening a cache using a URL.

Directories

Path Synopsis
internal
gcerrors
Package gcerrors provides error handling for the gocache package.
Package gcerrors provides error handling for the gocache package.
logext
Package logext provides a custom log.Logger interface for debug logging.
Package logext provides a custom log.Logger interface for debug logging.
urlparser
Package urlparser provides utilities for parsing URL query parameters into a given struct.
Package urlparser provides utilities for parsing URL query parameters into a given struct.
memcache module
pkg
driver
Package driver defines an interface for cache implementations, providing a standardized way to interact with different caching mechanisms.
Package driver defines an interface for cache implementations, providing a standardized way to interact with different caching mechanisms.
drivertest
Package drivertest provides conformance tests for cache implementations.
Package drivertest provides conformance tests for cache implementations.
keymod
Package keymod provides functions for modifying keys.
Package keymod provides functions for modifying keys.
ramcache module
redis module
rediscluster module

Jump to

Keyboard shortcuts

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