cache

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Cache Module

The cache module provides an enterprise-grade caching and distributed locking solution for microservices. It is designed to be highly concurrent, memory-safe, and framework-agnostic.

Features

  1. Local Memory Cache (MemoryCache):
    • Powered by Ristretto.
    • High performance and lock-free admission.
    • Built-in MaxCost to prevent Out-Of-Memory (OOM) issues.
    • Built-in TTL (Time-To-Live).
    • TinyLFU eviction policy for superior cache hit ratios.
  2. Distributed Cache (RedisCache):
    • Reuses existing redis.UniversalClient.
  3. Distributed Lock (RedisLock):
    • Atomic mutual exclusion across multiple nodes.
    • Prevents race conditions.
    • Safe token-based Release/Extend logic (Redlock concept) via Lua scripts.

Installation

This module automatically pulls the required dependencies:

go get github.com/thanhbvha/go-common/cache

Basic Usage

1. Local In-Memory Cache (Ristretto)
package main

import (
	"context"
	"fmt"
	"time"
	"github.com/thanhbvha/go-common/cache"
)

func main() {
	ctx := context.Background()

	// Initialize cache with a maximum capacity of 100MB
	memCache, err := cache.NewMemoryCache(100 * 1024 * 1024)
	if err != nil {
		panic(err)
	}

	// Set a value with a 5-minute TTL
	memCache.Set(ctx, "session:123", "user_data_here", 5*time.Minute)

	// Note: Ristretto handles admissions asynchronously. Allow a tiny sleep in tests.
	time.Sleep(10 * time.Millisecond)

	// Retrieve the value
	val, err := memCache.Get(ctx, "session:123")
	if err == cache.ErrNotFound {
		fmt.Println("Cache miss")
	} else {
		fmt.Println("Cache hit:", val)
	}
}
2. Distributed Lock

Used to ensure only one worker processes a specific task in a distributed environment (e.g., cron jobs, payment processing).

package main

import (
	"context"
	"fmt"
	"time"
	"github.com/redis/go-redis/v9"
	"github.com/thanhbvha/go-common/cache"
)

func processPayment(ctx context.Context, redisClient redis.UniversalClient, orderID string) {
	lockKey := "lock:payment:" + orderID
	
	// Initialize a new lock instance for this operation
	lock := cache.NewRedisLock(redisClient)

	// Attempt to acquire the lock for 10 seconds
	acquired, err := lock.Acquire(ctx, lockKey, 10*time.Second)
	if err != nil || !acquired {
		fmt.Println("Payment is already being processed by another node.")
		return
	}

	// ALWAYS ensure the lock is released when the function finishes
	defer lock.Release(ctx, lockKey)

	// -----------------------------
	// DO CRITICAL WORK HERE
	// -----------------------------
	fmt.Println("Processing payment exclusively for order:", orderID)

	// If the work takes longer than expected, you can extend the lock:
	// lock.Extend(ctx, lockKey, 10*time.Second)
}

Documentation

Overview

Package cache provides JSON-aware helper functions built on top of the Cache interface. These helpers automatically serialize/deserialize values using encoding/json, allowing any JSON-serializable type to be stored without manual marshaling.

Package cache provides a multi-level caching system and distributed lock implementation.

It defines a unified Cache interface that can be implemented by both local memory engines (like Ristretto) and remote distributed engines (like Redis). It also provides a DistributedLock interface for concurrency control across nodes.

Basic usage:

localCache, _ := cache.NewMemoryCache(100 * 1024 * 1024) // 100MB
localCache.Set(ctx, "key", "value", 5*time.Minute)
val, err := localCache.Get(ctx, "key")

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLockAcquisitionFailed is returned when the lock is already held by another client.
	ErrLockAcquisitionFailed = errors.New("cache: failed to acquire distributed lock")
)
View Source
var (
	// ErrNotFound is returned when a requested key does not exist in the cache.
	ErrNotFound = errors.New("cache: key not found")
)

Functions

func GetJSON added in v0.15.0

func GetJSON[T any](ctx context.Context, c Cache, key string, dest *T) error

GetJSON retrieves a value from the cache and deserializes it from JSON into dest. dest must be a pointer. Returns ErrNotFound if the key does not exist.

Example:

var user UserProfile
err := cache.GetJSON(ctx, myCache, "user:123", &user)
if errors.Is(err, cache.ErrNotFound) { ... }

func GetOrSetJSON added in v0.15.0

func GetOrSetJSON[T any](ctx context.Context, c Cache, key string, ttl time.Duration, fetch func() (T, error)) (T, error)

GetOrSetJSON retrieves a value from cache; on miss, calls fetch() to compute the value, stores it, and returns it. Useful for the cache-aside pattern.

Example:

user, err := cache.GetOrSetJSON(ctx, myCache, "user:123", 5*time.Minute, func() (*User, error) {
    return userRepo.FindByID(ctx, 123)
})

func SetJSON added in v0.15.0

func SetJSON[T any](ctx context.Context, c Cache, key string, value T, ttl time.Duration) error

SetJSON serializes value to JSON and stores it in the cache with the given TTL. A TTL of 0 means the key does not expire.

Example:

err := cache.SetJSON(ctx, myCache, "user:123", user, 5*time.Minute)

Types

type Cache

type Cache interface {
	// Get retrieves a value from the cache. Returns an error (e.g., ErrNotFound) if not found.
	Get(ctx context.Context, key string) (string, error)

	// Set stores a value in the cache with an optional Time-To-Live (TTL).
	// A TTL of 0 means the key does not expire.
	Set(ctx context.Context, key string, value string, ttl time.Duration) error

	// Delete removes a key from the cache.
	Delete(ctx context.Context, key string) error

	// Clear completely flushes the cache.
	Clear(ctx context.Context) error

	// Close releases resources held by the cache engine (e.g. background goroutines).
	// It must be called when the cache is no longer needed.
	Close() error
}

Cache defines the standard behavior for a caching engine (either local or remote).

type DistributedLock

type DistributedLock interface {
	// Acquire attempts to acquire the lock with a given TTL.
	// Returns true if successfully acquired, false otherwise.
	Acquire(ctx context.Context, key string, ttl time.Duration) (bool, error)

	// Release releases the lock.
	Release(ctx context.Context, key string) error

	// Extend attempts to extend the TTL of a lock currently held by the caller.
	Extend(ctx context.Context, key string, ttl time.Duration) (bool, error)
}

DistributedLock defines the behavior for a cluster-wide mutual exclusion lock.

type MemoryCache

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

MemoryCache implements the Cache interface using dgraph-io/ristretto.

func NewMemoryCache

func NewMemoryCache(maxCostBytes int64) (*MemoryCache, error)

NewMemoryCache creates a new in-memory cache with bounded max cost (in bytes). Note: It is highly concurrent and uses TinyLFU for optimal cache admission.

func (*MemoryCache) Clear

func (m *MemoryCache) Clear(ctx context.Context) error

Clear completely flushes the cache.

func (*MemoryCache) Close added in v0.11.0

func (m *MemoryCache) Close() error

Close releases resources held by the Ristretto cache, stopping its background goroutines.

func (*MemoryCache) Delete

func (m *MemoryCache) Delete(ctx context.Context, key string) error

Delete removes a key from the cache.

func (*MemoryCache) Get

func (m *MemoryCache) Get(ctx context.Context, key string) (string, error)

Get retrieves a string value from the cache.

func (*MemoryCache) Set

func (m *MemoryCache) Set(ctx context.Context, key string, value string, ttl time.Duration) error

Set stores a string value in the cache. Ristretto requires a 'cost' for each item. We use the length of the string as the cost.

type RedisCache

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

RedisCache implements the Cache interface using Redis.

func NewRedisCache

func NewRedisCache(client redis.UniversalClient) *RedisCache

NewRedisCache creates a new remote cache instance using a provided Redis client. This allows reusing the connection pool from the existing db/redis module.

func (*RedisCache) Clear

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

Clear flushes the current Redis database. WARNING: Use with caution.

func (*RedisCache) Close added in v0.11.0

func (r *RedisCache) Close() error

Close is a no-op for RedisCache. The lifecycle of the underlying Redis client is managed externally (e.g. by the redis.Client wrapper); do not close it here.

func (*RedisCache) Delete

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

Delete removes a key from Redis.

func (*RedisCache) Get

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

Get retrieves a string value from Redis.

func (*RedisCache) Set

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

Set stores a string value in Redis with an optional TTL. A TTL of 0 means the key does not expire.

type RedisLock

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

RedisLock implements DistributedLock using Redis SETNX with a random token to prevent accidental release.

func NewRedisLock

func NewRedisLock(client redis.UniversalClient) *RedisLock

NewRedisLock creates a new DistributedLock instance.

func (*RedisLock) Acquire

func (l *RedisLock) Acquire(ctx context.Context, key string, ttl time.Duration) (bool, error)

Acquire attempts to acquire a lock for a given key with a specified TTL.

func (*RedisLock) Extend

func (l *RedisLock) Extend(ctx context.Context, key string, ttl time.Duration) (bool, error)

Extend extends the TTL of a lock, ensuring the caller actually holds the lock via token check.

func (*RedisLock) Release

func (l *RedisLock) Release(ctx context.Context, key string) error

Release releases the lock using a Lua script to ensure atomic check-and-delete. It ensures that a client only deletes the lock if it holds the correct token.

Jump to

Keyboard shortcuts

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