cache

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package cache provides Redis caching with protobuf serialization for CQI infrastructure. It supports storing and retrieving protocol buffer messages with configurable TTL, cache-aside patterns, and health checking.

Example usage:

cfg := config.CacheConfig{
    Host: "localhost",
    Port: 6379,
    DB:   0,
}

c, err := cache.NewRedis(ctx, cfg)
if err != nil {
    log.Fatal(err)
}
defer c.Close()

// Store a protobuf message
user := &pb.User{Id: "123", Name: "John"}
err = c.Set(ctx, "user:123", user, 5*time.Minute)

// Retrieve the message
var retrieved pb.User
err = c.Get(ctx, "user:123", &retrieved)

// Use cache-aside pattern
key := cache.Key("user", userID)
err = c.GetOrLoad(ctx, key, &user, 5*time.Minute, func(ctx context.Context) (proto.Message, error) {
    return db.GetUser(ctx, userID)
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckHealthWithTimeout

func CheckHealthWithTimeout(cache Cache, timeout time.Duration) error

CheckHealthWithTimeout performs a health check with the specified timeout. This is a convenience wrapper that creates a context with timeout.

func Key

func Key(prefix string, parts ...string) string

Key builds a consistent cache key by joining a prefix and parts with colons. This ensures cache keys follow a consistent naming convention across the application.

Example:

key := cache.Key("user", userID)                    // "user:123"
key := cache.Key("portfolio", portfolioID, "stats") // "portfolio:abc:stats"

Empty parts are filtered out to prevent double colons.

Types

type Cache

type Cache interface {
	// Get retrieves a cached protobuf message by key and unmarshals it into dest.
	// Returns an error if the key doesn't exist or deserialization fails.
	// The dest parameter must be a pointer to a protobuf message.
	Get(ctx context.Context, key string, dest proto.Message) error

	// Set stores a protobuf message in the cache with the specified TTL.
	// The message is serialized to wire format before storage.
	// A TTL of 0 means no expiration.
	Set(ctx context.Context, key string, value proto.Message, ttl time.Duration) error

	// Delete removes a key from the cache.
	// Returns nil if the key doesn't exist.
	Delete(ctx context.Context, key string) error

	// Exists checks if a key exists in the cache.
	// Returns true if the key exists, false otherwise.
	Exists(ctx context.Context, key string) (bool, error)

	// GetOrLoad retrieves a value from cache, or loads it using the provided loader function if not found.
	// The loaded value is automatically cached with the specified TTL.
	// This implements the cache-aside pattern.
	GetOrLoad(ctx context.Context, key string, dest proto.Message, ttl time.Duration, loader func(context.Context) (proto.Message, error)) error

	// CheckHealth verifies cache connectivity and returns an error if unavailable.
	CheckHealth(ctx context.Context) error

	// Close releases all resources associated with the cache.
	Close() error
}

Cache defines the interface for cache operations with protobuf message support. All methods respect context cancellation and timeout.

type HealthChecker

type HealthChecker interface {
	CheckHealth(ctx context.Context) error
}

HealthChecker defines the interface for cache health checking. This can be used with health check frameworks.

type RedisCache

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

RedisCache implements the Cache interface using Redis as the backend.

func NewRedis

func NewRedis(ctx context.Context, cfg config.CacheConfig) (*RedisCache, error)

NewRedis creates a new Redis cache client with the given configuration. It accepts context for cancellation during connection establishment.

The connection is lazy - it won't fail if Redis is temporarily unavailable, but will retry on first operation according to MaxRetries config.

func (*RedisCache) Check

func (r *RedisCache) Check(ctx context.Context) error

Check implements the health.Checker interface for the Redis cache. This allows the cache to be used directly with the health check framework.

Example usage:

import "github.com/Combine-Capital/cqi/pkg/health"

h := health.New()
h.RegisterChecker("cache", redisCache)

func (*RedisCache) CheckHealth

func (r *RedisCache) CheckHealth(ctx context.Context) error

CheckHealth verifies cache connectivity using Redis PING command.

func (*RedisCache) Close

func (r *RedisCache) Close() error

Close releases all resources associated with the cache.

func (*RedisCache) Delete

func (r *RedisCache) Delete(ctx context.Context, key string) error

Delete removes a key from the cache.

func (*RedisCache) Exists

func (r *RedisCache) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists in the cache.

func (*RedisCache) Get

func (r *RedisCache) Get(ctx context.Context, key string, dest proto.Message) error

Get retrieves a cached protobuf message by key and unmarshals it into dest.

func (*RedisCache) GetOrLoad

func (r *RedisCache) GetOrLoad(ctx context.Context, key string, dest proto.Message, ttl time.Duration, loader func(context.Context) (proto.Message, error)) error

GetOrLoad retrieves a value from cache, or loads it using the provided loader function if not found. The loaded value is automatically cached with the specified TTL. This implements the cache-aside pattern.

func (*RedisCache) Set

func (r *RedisCache) Set(ctx context.Context, key string, value proto.Message, ttl time.Duration) error

Set stores a protobuf message in the cache with the specified TTL.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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