cache

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: MIT Imports: 8 Imported by: 0

README

Cache Package

The cache package provides a generic in-memory cache implementation with expiration for frequently accessed data.

Overview

This package implements a simple in-memory cache with the following features:

  • Generic support for caching any type of data
  • Configurable time-to-live (TTL) for cache items
  • Automatic cleanup of expired items
  • Maximum size limit with configurable eviction strategies
  • Support for OpenTelemetry tracing
  • Fluent interface for configuration
  • Thread-safe implementation
  • Middleware functions for easy integration

Usage

Basic Usage
import (
    "context"
    "github.com/abitofhelp/servicelib/cache"
    "github.com/abitofhelp/servicelib/logging"
    "go.uber.org/zap"
    "time"
)

// Create a cache
cfg := cache.DefaultConfig().
    WithEnabled(true).
    WithTTL(5 * time.Minute).
    WithMaxSize(1000)

logger := logging.NewContextLogger(zap.NewNop())
options := cache.DefaultOptions().
    WithName("user-cache").
    WithLogger(logger)

// Create a cache for User objects
userCache := cache.NewCache[User](cfg, options)

// Set a value in the cache
ctx := context.Background()
userCache.Set(ctx, "user:123", user)

// Get a value from the cache
user, found := userCache.Get(ctx, "user:123")
if found {
    // Use the cached user
} else {
    // User not found in cache
}

// Set a value with a custom TTL
userCache.SetWithTTL(ctx, "user:456", user, 10 * time.Minute)

// Delete a value from the cache
userCache.Delete(ctx, "user:123")

// Clear the entire cache
userCache.Clear(ctx)

// Get the number of items in the cache
count := userCache.Size()

// Shutdown the cache (stops the cleanup goroutine)
userCache.Shutdown()
Using Cache Middleware

The package provides middleware functions to simplify caching function results:

// Cache the result of a function
user, err := cache.WithCache(ctx, userCache, "user:123", func(ctx context.Context) (User, error) {
    // This function will only be called if the key is not in the cache
    return userService.GetUser(ctx, "123")
})

// Cache the result with a custom TTL
user, err := cache.WithCacheTTL(ctx, userCache, "user:123", 10 * time.Minute, func(ctx context.Context) (User, error) {
    return userService.GetUser(ctx, "123")
})

Configuration

The cache can be configured using the Config struct and the fluent interface:

cfg := cache.DefaultConfig().
    WithEnabled(true).                  // Enable/disable the cache
    WithTTL(5 * time.Minute).           // Default time-to-live for cache items
    WithMaxSize(1000).                  // Maximum number of items in the cache
    WithPurgeInterval(1 * time.Minute)  // Interval at which expired items are purged

Eviction Strategies

The cache supports different eviction strategies when the maximum size is reached:

  • LRU (Least Recently Used): Evicts the least recently used item
  • LFU (Least Frequently Used): Evicts the least frequently used item
  • FIFO (First In, First Out): Evicts the first item added to the cache
  • Random: Evicts a random item

OpenTelemetry Integration

The cache supports OpenTelemetry tracing:

import (
    "go.opentelemetry.io/otel/trace"
)

// Create a tracer
tracer := otelTracer // Your OpenTelemetry tracer

// Configure the cache with the tracer
options := cache.DefaultOptions().
    WithName("user-cache").
    WithLogger(logger).
    WithOtelTracer(tracer)

userCache := cache.NewCache[User](cfg, options)

Thread Safety

The cache is thread-safe and can be used concurrently from multiple goroutines.

Performance Considerations

  • The cache uses a map internally, so lookups are O(1)
  • The cache uses a read-write mutex to ensure thread safety, so concurrent reads are allowed but writes are exclusive
  • The cleanup goroutine runs at the configured interval to remove expired items
  • When the maximum size is reached, an item will be evicted according to the configured eviction strategy

Documentation

Overview

Package cache provides functionality for caching frequently accessed data.

This package implements a simple in-memory cache with expiration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithCache

func WithCache[T any](ctx context.Context, cache *Cache[T], key string, fn func(ctx context.Context) (T, error)) (T, error)

WithCache is a middleware that adds caching to a function

func WithCacheTTL

func WithCacheTTL[T any](ctx context.Context, cache *Cache[T], key string, ttl time.Duration, fn func(ctx context.Context) (T, error)) (T, error)

WithCacheTTL is a middleware that adds caching with a custom TTL to a function

Types

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}

Cache is a simple in-memory cache with expiration

func NewCache

func NewCache[T any](config Config, options Options) *Cache[T]

NewCache creates a new cache with the given configuration

func (*Cache[T]) Clear

func (c *Cache[T]) Clear(ctx context.Context)

Clear removes all items from the cache

func (*Cache[T]) Delete

func (c *Cache[T]) Delete(ctx context.Context, key string)

Delete removes an item from the cache

func (*Cache[T]) Get

func (c *Cache[T]) Get(ctx context.Context, key string) (T, bool)

Get retrieves an item from the cache

func (*Cache[T]) Set

func (c *Cache[T]) Set(ctx context.Context, key string, value T)

Set adds an item to the cache with the default expiration time

func (*Cache[T]) SetWithTTL

func (c *Cache[T]) SetWithTTL(ctx context.Context, key string, value T, ttl time.Duration)

SetWithTTL adds an item to the cache with a custom expiration time

func (*Cache[T]) Shutdown

func (c *Cache[T]) Shutdown()

Shutdown stops the cleanup timer

func (*Cache[T]) Size

func (c *Cache[T]) Size() int

Size returns the number of items in the cache

type Config

type Config struct {
	// Enabled determines if the cache is enabled
	Enabled bool
	// TTL is the default time-to-live for cache items
	TTL time.Duration
	// MaxSize is the maximum number of items in the cache
	MaxSize int
	// PurgeInterval is the interval at which expired items are purged
	PurgeInterval time.Duration
}

Config contains cache configuration parameters

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default cache configuration

func (Config) WithEnabled

func (c Config) WithEnabled(enabled bool) Config

WithEnabled sets whether the cache is enabled

func (Config) WithMaxSize

func (c Config) WithMaxSize(maxSize int) Config

WithMaxSize sets the maximum number of items in the cache

func (Config) WithPurgeInterval

func (c Config) WithPurgeInterval(purgeInterval time.Duration) Config

WithPurgeInterval sets the interval at which expired items are purged

func (Config) WithTTL

func (c Config) WithTTL(ttl time.Duration) Config

WithTTL sets the default time-to-live for cache items

type EvictionStrategy

type EvictionStrategy int

EvictionStrategy defines the strategy for evicting items when the cache is full

const (
	// LRU evicts the least recently used item
	LRU EvictionStrategy = iota
	// LFU evicts the least frequently used item
	LFU
	// FIFO evicts the first item added to the cache
	FIFO
	// Random evicts a random item
	Random
)

type Item

type Item[T any] struct {
	Value      T
	Expiration int64
}

Item represents a cached item with its value and expiration time

type Options

type Options struct {
	// Logger is used for logging cache operations
	Logger *logging.ContextLogger
	// Tracer is used for tracing cache operations
	Tracer telemetry.Tracer
	// Name is the name of the cache
	Name string
}

Options contains additional options for the cache

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns default options for cache operations

func (Options) WithLogger

func (o Options) WithLogger(logger *logging.ContextLogger) Options

WithLogger sets the logger for the cache

func (Options) WithName

func (o Options) WithName(name string) Options

WithName sets the name of the cache

func (Options) WithOtelTracer

func (o Options) WithOtelTracer(tracer trace.Tracer) Options

WithOtelTracer returns Options with an OpenTelemetry tracer

Jump to

Keyboard shortcuts

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