cache

package
v1.3.35 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2025 License: MIT Imports: 13 Imported by: 0

README

cache

memory and redis cache libraries.

Features

  • Redis and in-memory cache implementations
  • Distributed locking with redsync
  • Bloom filter support for reducing cache misses
  • Automatic serialization with multiple encoding options
  • Comprehensive logging and error handling

Example of use


// Choose to create a memory or redis cache depending on CType
cache := cache.NewUserExampleCache(&model.CacheType{
  CType: "redis",
  Rdb:   c.RedisClient,
})

// -----------------------------------------------------------------------------------------

type userExampleDao struct {
	db    *gorm.DB
	cache cache.UserExampleCache
}

// NewUserExampleDao creating the dao interface
func NewUserExampleDao(db *gorm.DB, cache cache.UserExampleCache) UserExampleDao {
	return &userExampleDao{db: db, cache: cache}
}

// GetByID get a record based on id
func (d *userExampleDao) GetByID(ctx context.Context, id uint64) (*model.UserExample, error) {
	record, err := d.cache.Get(ctx, id)
	if err == nil {
		return record, nil
	}

	if errors.Is(err, model.ErrCacheNotFound) {
		// get from mysql
		table := &model.UserExample{}
		err = d.db.WithContext(ctx).Where("id = ?", id).First(table).Error
		if err != nil {
			// if data is empty, set not found cache to prevent cache penetration(preventing Cache Penetration)
			if errors.Is(err, model.ErrRecordNotFound) {
				err = d.cache.SetCacheWithNotFound(ctx, id)
				if err != nil {
					return nil, err
				}
				return nil, model.ErrRecordNotFound
			}
			return nil, err
		}

		// set cache
		err = d.cache.Set(ctx, id, table, 10*time.Minute)
		if err != nil {
			return nil, fmt.Errorf("cache.Set error: %v, id=%d", err, id)
		}
		return table, nil
	} else if errors.Is(err, cacheBase.ErrPlaceholder) {
		return nil, model.ErrRecordNotFound
	}

	// fail fast, if cache error return, don't request to db
	return nil, err
}

Bloom Filter Features

The Redis cache implementation includes a Bloom filter to reduce unnecessary Redis queries:

  • False Positive Rate: Configured at 0.1% by default
  • Expected Elements: 10,000,000 by default
  • Auto-initialization: Automatically populated from existing Redis keys
  • Statistics Tracking: Tracks hits, misses, false positives, and true negatives
  • Rebuilding: Supports both synchronous and asynchronous rebuilding of the filter
  • Health Monitoring: Provides health metrics to monitor filter effectiveness

Bloom Filter Methods

  • InitBloomFilter: Initialize the Bloom filter from existing Redis keys
  • AddToBloomFilter: Add a key to the Bloom filter
  • BloomFilter: Test if a key might be in the cache
  • GetBloomFilterStats: Get statistics about the Bloom filter usage
  • CheckBloomFilterHealth: Get health metrics of the Bloom filter
  • RebuildBloomFilter: Synchronously rebuild the Bloom filter
  • RebuildBloomFilterAsync: Asynchronously rebuild the Bloom filter

The Bloom filter helps reduce cache penetration and unnecessary database queries by quickly determining if a key definitely does not exist in the cache.

Documentation

Overview

Package cache is redis cache libraries.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultExpireTime default expiry time
	DefaultExpireTime = time.Hour * 24
	// DefaultNotFoundExpireTime expiry time when result is empty 1 minute,
	// often used for cache time when data is empty (cache pass-through)
	DefaultNotFoundExpireTime = time.Minute * 1
	// NotFoundPlaceholder placeholder
	NotFoundPlaceholder = "*"

	// DefaultClient generate a cache client, where keyPrefix is generally the business prefix
	DefaultClient Cache

	// ErrPlaceholder .
	ErrPlaceholder = errors.New("cache: placeholder")
)
View Source
var CacheNotFound = redis.Nil

CacheNotFound no hit cache

Functions

func BuildCacheKey

func BuildCacheKey(keyPrefix string, key string) (string, error)

BuildCacheKey construct a cache key with a prefix

func Del

func Del(ctx context.Context, keys ...string) error

Del multiple delete data

func DelByPrefix added in v1.1.78

func DelByPrefix(ctx context.Context, prefix string) error

DelByPrefix multiple delete data

func Get

func Get(ctx context.Context, key string, val interface{}) error

Get data

func GetLock added in v1.1.4

func GetLock(ctx context.Context, key string, options ...redsync.Option) (*redsync.Mutex, error)

func GetLoopLock added in v1.1.6

func GetLoopLock(ctx context.Context, key string, options ...redsync.Option) (*redsync.Mutex, error)

func MultiGet

func MultiGet(ctx context.Context, keys []string, valueMap interface{}) error

MultiGet multiple get data

func MultiSet

func MultiSet(ctx context.Context, valMap map[string]interface{}, expireTime time.Duration) error

MultiSet multiple set data

func Set

func Set(ctx context.Context, key string, val interface{}, expireTime time.Duration) error

Set data

func SetCacheWithNotFound

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

SetCacheWithNotFound .

Types

type Cache

type Cache interface {
	GetLoopLock(ctx context.Context, key string, options ...redsync.Option) (*redsync.Mutex, error)
	GetLock(ctx context.Context, key string, options ...redsync.Option) (*redsync.Mutex, error)
	Set(ctx context.Context, key string, val interface{}, expireTime time.Duration) error
	Get(ctx context.Context, key string, val interface{}) error
	MultiSet(ctx context.Context, valMap map[string]interface{}, expireTime time.Duration) error
	MultiGet(ctx context.Context, keys []string, valueMap interface{}) error
	Del(ctx context.Context, keys ...string) error
	DelByPrefix(ctx context.Context, prefix string) error
	SetCacheWithNotFound(ctx context.Context, key string) error
}

Cache driver interface

func NewRedisCache

func NewRedisCache(client *redis.Client, keyPrefix string, encode encoding.Encoding, newObject func() interface{}, options ...NewRedisCacheOption) Cache

NewRedisCache new a cache, client parameter can be passed in for unit testing

type NewRedisCacheOption added in v1.3.26

type NewRedisCacheOption func(*redisCache)

NewRedisCacheOption 是NewRedisCache的可选配置

func WithCacheLog added in v1.3.26

func WithCacheLog(log *zap.Logger) NewRedisCacheOption

WithCacheLog set log

Jump to

Keyboard shortcuts

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