cache

package
v0.0.0-...-a89d057 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 23 Imported by: ? modules, 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.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrCacheMiss = errors.New("cache miss")

ErrCacheMiss indicates a cache miss error

View Source
var ErrLockAcquireFailed = errors.New("failed to acquire distributed lock")

ErrLockAcquireFailed indicates failure to acquire lock

View Source
var SimpleTool = func(ctx *gin.Context) *Tool[any] {
	return NewCacheTool[any](ctx, defaultCaches, nil)
}

SimpleTool returns a multi-level cache tool (L1 In-Memory + L2 Redis if available).

Functions

func Del

func Del(key string) error

Del deletes a key from the default cache.

func DelCtx

func DelCtx(ctx context.Context, key string) error

DelCtx deletes a key from the default cache with context.

func Exists

func Exists(key string) (bool, error)

Exists checks if a key exists in the default cache.

func ExistsCtx

func ExistsCtx(ctx context.Context, key string) (bool, error)

ExistsCtx checks if a key exists in the default cache with context.

func Expire

func Expire(key string, expiration time.Duration) error

Expire sets expiration for a key in the default cache.

func ExpireCtx

func ExpireCtx(ctx context.Context, key string, expiration time.Duration) error

ExpireCtx sets expiration for a key in the default cache with context.

func Get

func Get[T any](key string) (T, error)

Get retrieves a value from the default cache.

func GetCtx

func GetCtx[T any](ctx context.Context, key string) (T, error)

GetCtx retrieves a value from the default cache with context.

func GetOrDefault

func GetOrDefault[T any](key string, defValue T) T

GetOrDefault retrieves a value from the default cache or returns defValue on error/miss.

func GetOrSet

func GetOrSet[T any](key string, expiration time.Duration, defaultVal T) (T, error)

GetOrSet retrieves a value or sets the default value if key misses.

func Incr

func Incr(key string) (int64, error)

Incr increments a counter in the default cache.

func IncrCtx

func IncrCtx(ctx context.Context, key string) (int64, error)

IncrCtx increments a counter in the default cache with context.

func Lock

func Lock(ctx context.Context, key string, ttl time.Duration, retryInterval, timeout time.Duration) (unlock func(), err error)

Lock blocks until lock is acquired or timeout is reached.

func Remember

func Remember[T any](key string, expiration time.Duration, fallback func() (T, error)) (T, error)

Remember retrieves data from the default cache. If cache misses, calls fallback, caches the result with Singleflight protection to prevent cache stampedes, and returns it.

func RememberCtx

func RememberCtx[T any](ctx context.Context, key string, expiration time.Duration, fallback func() (T, error)) (T, error)

RememberCtx retrieves data from the default cache with context and Singleflight protection.

func RememberWithCache

func RememberWithCache[T any](c Cache[T], key string, expiration time.Duration, fallback func() (T, error)) (T, error)

RememberWithCache retrieves data from the specified cache with Singleflight protection.

func RestRedisInstance

func RestRedisInstance()

func Set

func Set[T any](key string, value T, expiration time.Duration) error

Set stores a value in the default cache.

func SetCtx

func SetCtx[T any](ctx context.Context, key string, value T, expiration time.Duration) error

SetCtx stores a value in the default cache with context.

func TryLock

func TryLock(ctx context.Context, key string, ttl time.Duration) (unlock func(), ok bool, err error)

TryLock attempts to acquire a lock on key immediately without blocking. Returns an unlock function, a boolean indicating if lock was acquired, and any error encountered.

func WithLock

func WithLock(ctx context.Context, key string, ttl time.Duration, fn func() error) error

WithLock executes fn while holding a distributed lock on key. If Redis is configured, it uses Redis SETNX with expiration and safe Lua unlock. If Redis is not configured, it uses in-memory mutex lock with TTL.

func WithLockTimeout

func WithLockTimeout(ctx context.Context, key string, ttl, timeout time.Duration, fn func() error) error

WithLockTimeout executes fn while acquiring a lock with retry until timeout.

Types

type Agg

type Agg string
const (
	AggSum   Agg = "sum"
	AggAvg   Agg = "avg"
	AggMax   Agg = "max"
	AggMin   Agg = "min"
	AggCount Agg = "count"
	AggTotal Agg = "total"
)

type AggField

type AggField struct {
	Field string
	Agg   Agg
	Alias string
}

type Cache

type Cache[T any] interface {
	IsInitialized() bool
	Keys() ([]string, error)
	Items() map[string]T
	Get(key string) (T, error)
	Set(key string, value T, expiration time.Duration) error
	Del(key string) error
	Exists(key string) (bool, error)
	RPush(key string, value T) error
	BRPop(timeout time.Duration, key string) (value T, err error)
	Incr(key string) (int64, error)
	Expire(key string, expiration time.Duration) error
	Flush() error
}

Cache is a generic cache interface that defines basic cache operations

func GetDefaultCache

func GetDefaultCache[T any](ctx context.Context) Cache[T]

GetDefaultCache returns the default cache instance for type T. If Redis is configured and initialized, it returns the Redis cache. Otherwise, it returns the shared in-memory cache.

func New

func New[T any](t Type, args ...any) Cache[T]

type GoCache

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

func NewGoCache

func NewGoCache[T any](defaultExpiration, cleanupInterval time.Duration) *GoCache[T]

func NewSharedGoCache

func NewSharedGoCache[T any]() *GoCache[T]

func (*GoCache[T]) BRPop

func (g *GoCache[T]) BRPop(timeout time.Duration, key string) (T, error)

func (*GoCache[T]) Del

func (g *GoCache[T]) Del(key string) error

func (*GoCache[T]) Exists

func (g *GoCache[T]) Exists(key string) (bool, error)

func (*GoCache[T]) Expire

func (g *GoCache[T]) Expire(key string, expiration time.Duration) error

func (*GoCache[T]) Flush

func (g *GoCache[T]) Flush() error

func (*GoCache[T]) Get

func (g *GoCache[T]) Get(key string) (T, error)

func (*GoCache[T]) Incr

func (g *GoCache[T]) Incr(key string) (int64, error)

func (*GoCache[T]) IsInitialized

func (g *GoCache[T]) IsInitialized() bool

func (*GoCache[T]) Items

func (g *GoCache[T]) Items() map[string]T

func (*GoCache[T]) Keys

func (g *GoCache[T]) Keys() ([]string, error)

func (*GoCache[T]) RPush

func (g *GoCache[T]) RPush(key string, value T) error

func (*GoCache[T]) Set

func (g *GoCache[T]) Set(key string, value T, expiration time.Duration) error

type Granularity

type Granularity string
const (
	GranularityMinute    Granularity = "minute"
	GranularityHour      Granularity = "hour"
	GranularityDay       Granularity = "day"
	GranularityWeek      Granularity = "week"
	GranularityMonth     Granularity = "month"
	GranularityYear      Granularity = "year"
	Granularity5Minutes  Granularity = "5m"
	Granularity10Minutes Granularity = "10m"
	Granularity30Minutes Granularity = "30m"
)

type JSONFileCache

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

func NewJSONCache

func NewJSONCache[T any](cacheType string) (*JSONFileCache[T], error)

func (*JSONFileCache[T]) BRPop

func (c *JSONFileCache[T]) BRPop(timeout time.Duration, key string) (value T, err error)

func (*JSONFileCache[T]) Del

func (c *JSONFileCache[T]) Del(key string) error

func (*JSONFileCache[T]) Exists

func (c *JSONFileCache[T]) Exists(key string) (bool, error)

func (*JSONFileCache[T]) Expire

func (c *JSONFileCache[T]) Expire(key string, expiration time.Duration) error

func (*JSONFileCache[T]) Flush

func (c *JSONFileCache[T]) Flush() error

func (*JSONFileCache[T]) Get

func (c *JSONFileCache[T]) Get(key string) (T, error)

func (*JSONFileCache[T]) Incr

func (c *JSONFileCache[T]) Incr(key string) (int64, error)

func (*JSONFileCache[T]) IsInitialized

func (c *JSONFileCache[T]) IsInitialized() bool

func (*JSONFileCache[T]) Items

func (c *JSONFileCache[T]) Items() map[string]T

func (*JSONFileCache[T]) Keys

func (c *JSONFileCache[T]) Keys() ([]string, error)

func (*JSONFileCache[T]) RPush

func (c *JSONFileCache[T]) RPush(key string, value T) error

func (*JSONFileCache[T]) Set

func (c *JSONFileCache[T]) Set(key string, value T, expiration time.Duration) error

type LoaderFunc

type LoaderFunc[T any] func(key string) (T, error)

LoaderFunc is a function type for loading data from an external source

type PageCache

type PageCache[T any] struct {
	Total int64 `json:"total"`
	Page  int64 `json:"page"`
	Size  int64 `json:"size"`
	Items []*T  `json:"items"`
}

func (*PageCache[T]) JSON

func (p *PageCache[T]) JSON() string

type PageGroupItem

type PageGroupItem struct {
	Group map[string]string  `json:"group"`
	Value map[string]float64 `json:"value"`
}

type PageSorter

type PageSorter struct {
	SortField string
	Asc       bool
	Expr      string // optional raw expression
}

func PageSorterAsc

func PageSorterAsc(field string) PageSorter

func PageSorterDesc

func PageSorterDesc(field string) PageSorter

type PageTimeItem

type PageTimeItem struct {
	At    string             `json:"at"`
	Value map[string]float64 `json:"value"`
}

type Pager

type Pager[T any] interface {
	Put(value T) error
	Find(page, size int64, conditions map[string]any, sort ...PageSorter) (*PageCache[T], error)
	Get(conditions map[string]any) (*T, error)
	Count(conditions map[string]any) (int64, error)
	Update(conditions map[string]any, value *T) error
	Delete(conditions map[string]any) error
	GroupByTime(conditions map[string]any, from, to time.Time, granularity Granularity, agg Agg, fields ...string) ([]*PageTimeItem, error)
	GroupByFields(conditions map[string]any, groupFields []string, aggFields []AggField, page, size int64, sorts ...PageSorter) (*PageCache[PageGroupItem], error)
}

func NewPager

func NewPager[T any](ctx context.Context, t Type, args ...any) Pager[T]

type Queue

type Queue[T any] struct {
	Items []T
}

type RedisCache

type RedisCache[T any] struct {
	Client *redis.Client
	Ctx    context.Context
}

func GetRedisInstance

func GetRedisInstance[T any](ctx context.Context) *RedisCache[T]

func (*RedisCache[T]) AddDelayed

func (r *RedisCache[T]) AddDelayed(queue string, value T, score float64) error

func (*RedisCache[T]) BLPop

func (r *RedisCache[T]) BLPop(timeout time.Duration, queue string) (value T, err error)

func (*RedisCache[T]) BLPopCtx

func (r *RedisCache[T]) BLPopCtx(ctx context.Context, timeout time.Duration, queue string) (value T, err error)

BLPopCtx consumes the oldest item from a Redis list. It is kept separate from BRPopCtx because RPUSH + BRPOP has LIFO semantics, while cache queues and the message broker promise FIFO delivery.

func (*RedisCache[T]) BRPop

func (r *RedisCache[T]) BRPop(timeout time.Duration, queue string) (value T, err error)

func (*RedisCache[T]) BRPopCtx

func (r *RedisCache[T]) BRPopCtx(ctx context.Context, timeout time.Duration, queue string) (value T, err error)

func (*RedisCache[T]) Del

func (r *RedisCache[T]) Del(key string) error

func (*RedisCache[T]) Exists

func (r *RedisCache[T]) Exists(key string) (bool, error)

func (*RedisCache[T]) Expire

func (r *RedisCache[T]) Expire(key string, expiration time.Duration) error

func (*RedisCache[T]) Flush

func (r *RedisCache[T]) Flush() error

func (*RedisCache[T]) Get

func (r *RedisCache[T]) Get(key string) (T, error)

func (*RedisCache[T]) GetCtx

func (r *RedisCache[T]) GetCtx() context.Context

func (*RedisCache[T]) Incr

func (r *RedisCache[T]) Incr(key string) (int64, error)

func (*RedisCache[T]) IsInitialized

func (r *RedisCache[T]) IsInitialized() bool

func (*RedisCache[T]) Items

func (r *RedisCache[T]) Items() map[string]T

func (*RedisCache[T]) Keys

func (r *RedisCache[T]) Keys() ([]string, error)

func (*RedisCache[T]) LPop

func (r *RedisCache[T]) LPop(queue string) (value T, err error)

func (*RedisCache[T]) PopDueDelayed

func (r *RedisCache[T]) PopDueDelayed(queue string, now float64, limit int) ([]T, error)

func (*RedisCache[T]) RPush

func (r *RedisCache[T]) RPush(queue string, value T) error

func (*RedisCache[T]) Set

func (r *RedisCache[T]) Set(key string, value T, expiration time.Duration) error

type RedisConfig

type RedisConfig struct {
	Addr     string
	Password string
	DB       int
	PoolSize int
}

RedisConfig holds the Redis configuration parameters

type SQLiteCache

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

func NewSQLiteCache

func NewSQLiteCache[T any](cacheType string) (*SQLiteCache[T], error)

func (*SQLiteCache[T]) BRPop

func (c *SQLiteCache[T]) BRPop(sqliteTimeOut time.Duration, key string) (T, error)

func (*SQLiteCache[T]) Del

func (c *SQLiteCache[T]) Del(key string) error

func (*SQLiteCache[T]) Exists

func (c *SQLiteCache[T]) Exists(key string) (bool, error)

func (*SQLiteCache[T]) Expire

func (c *SQLiteCache[T]) Expire(key string, expiration time.Duration) error

func (*SQLiteCache[T]) Flush

func (c *SQLiteCache[T]) Flush() error

func (*SQLiteCache[T]) Get

func (c *SQLiteCache[T]) Get(key string) (T, error)

func (*SQLiteCache[T]) Incr

func (c *SQLiteCache[T]) Incr(key string) (int64, error)

func (*SQLiteCache[T]) IsInitialized

func (c *SQLiteCache[T]) IsInitialized() bool

func (*SQLiteCache[T]) Items

func (c *SQLiteCache[T]) Items() map[string]T

func (*SQLiteCache[T]) Keys

func (c *SQLiteCache[T]) Keys() ([]string, error)

func (*SQLiteCache[T]) RPush

func (c *SQLiteCache[T]) RPush(key string, value T) error

func (*SQLiteCache[T]) Set

func (c *SQLiteCache[T]) Set(key string, value T, expiration time.Duration) error

type SQLiteCachePage

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

func NewSQLiteCachePage

func NewSQLiteCachePage[T any](name string) (*SQLiteCachePage[T], error)

NewSQLiteCachePage Create a new SQLite cache page with the given name.

func (*SQLiteCachePage[T]) Count

func (c *SQLiteCachePage[T]) Count(conditions map[string]any) (int64, error)

func (*SQLiteCachePage[T]) Delete

func (c *SQLiteCachePage[T]) Delete(conditions map[string]any) error

func (*SQLiteCachePage[T]) Find

func (c *SQLiteCachePage[T]) Find(page, size int64, conditions map[string]any, sorts ...PageSorter) (*PageCache[T], error)

func (*SQLiteCachePage[T]) Get

func (c *SQLiteCachePage[T]) Get(conditions map[string]any) (*T, error)

func (*SQLiteCachePage[T]) GroupByFields

func (c *SQLiteCachePage[T]) GroupByFields(
	conditions map[string]any,
	groupFields []string,
	aggFields []AggField,
	page, size int64,
	sorts ...PageSorter,
) (*PageCache[PageGroupItem], error)

func (*SQLiteCachePage[T]) GroupByTime

func (c *SQLiteCachePage[T]) GroupByTime(
	conditions map[string]any,
	from, to time.Time,
	granularity Granularity,
	agg Agg,
	fields ...string,
) ([]*PageTimeItem, error)

func (*SQLiteCachePage[T]) Put

func (c *SQLiteCachePage[T]) Put(value T) error

func (*SQLiteCachePage[T]) Update

func (c *SQLiteCachePage[T]) Update(conditions map[string]any, value *T) error

type Tool

type Tool[T any] struct {
	Ctx context.Context
	// contains filtered or unexported fields
}

Tool is a management tool for multi-level cache

func NewCacheTool

func NewCacheTool[T any](ctx context.Context, caches []Cache[T], loader LoaderFunc[T]) *Tool[T]

NewCacheTool creates a new Tool instance

func (*Tool[T]) Delete

func (c *Tool[T]) Delete(key string) error

Delete removes data from all cache levels

func (*Tool[T]) Get

func (c *Tool[T]) Get(key string, expiration time.Duration) (T, error)

Get retrieves data from the cache, searching each level in order, and loads from the loader if all levels miss

func (*Tool[T]) Remember

func (c *Tool[T]) Remember(key string, expiration time.Duration, fallback func() (T, error)) (T, error)

Remember retrieves data from multi-level cache or falls back to the loader function with singleflight protection

func (*Tool[T]) Set

func (c *Tool[T]) Set(key string, value T, expiration time.Duration) error

Set stores data in all cache levels

type Type

type Type string
const (
	Memory Type = "memory"
	Redis  Type = "redis"
	JSON   Type = "json"
	Sqlite Type = "sqlite"
)

Jump to

Keyboard shortcuts

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