memorycache

package module
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 10 Imported by: 0 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.

README

MemoryCache

logo
To the time to life, rather than to life in time.

中文

Build Status codecov

Description

Minimalist in-memory KV storage, powered by HashMap and Minimal Quad Heap.

Cache Eviction Policy:

  • Set evicts LRU keys on capacity overflow
  • Periodic cycle evicts expired keys

Design

  • Storage Data Limit: Limited by maximum capacity
  • Expiration Time: Supported
  • Cache Eviction Policy: LRU
  • Persistent: None
  • Locking Mechanism: Slicing + Mutual Exclusion Locking
  • HashMap, Heap and LinkedList (excluding user KVs) implemented in pointerless technology

Advantage

  • Simple and easy to use
  • High performance
  • Low memory usage
  • Uses a 4-ary min-heap to maintain expiration times. Compared to binary heaps, this reduces tree height and improves insertion performance.

Methods

  • Set : Set key-value pair with expiring time. If the key already exists, the value will be updated. Also the expiration time will be updated. exp<=0 means never expire.
  • SetWithCallback : Similar to Set, but with a callback function. Triggered on capacity overflow, expiration, deletion, or clear.
  • Get : Get value by key. If the key does not exist, the second return value will be false.
  • GetTTL : Get the expiration time of the key.
  • GetWithTTL : Get value by key. If the key exists, refreshes the expiration time.
  • UpdateTTL : Update the expiration time of the key. d<=0 means never expire.
  • Delete : Delete key-value pair by key.
  • GetOrCreate : Get value by key. If the key does not exist, the value will be created.
  • GetOrCreateWithCallback : Get value by key. If the key does not exist, the value will be created with an optional callback.
  • Clear : Clear all caches. Triggers ReasonCleared callback for alive non-expired elements.
  • Range : Iterate all key-value pairs in the cache.
  • Len : Get the current number of cached elements (may include expired but un-cleaned elements).
  • Stop : Stop the background goroutines, drain pending callbacks, and release resources. Do not use the instance after Stop.

Callbacks

Callbacks registered via SetWithCallback or GetOrCreateWithCallback are triggered on expiration, LRU eviction, explicit deletion, or Clear. Dispatch mode is controlled by WithAsyncCallback (default: async).

Async mode (WithAsyncCallback(true), default):

  • Dispatched through an internal task queue (queues.Queue).
  • Executed outside bucket locks — does not block cache operations or risk deadlocks from reentrant cache access.
  • The *Element is a snapshot copied before the entry is recycled.
  • Delivery is best-effort and unordered across keys; same hash shard is serialized (concurrency=1 per shard).
  • Panics are recovered and logged (WithRecovery).
  • Stop() drains pending callbacks (up to 30s timeout). After Stop, further mutations (if any) run callbacks synchronously so they are not silently dropped.

Sync mode (WithAsyncCallback(false)):

  • Callback runs inline under the bucket lock before the entry is recycled.
  • The *Element is a live reference valid only for the duration of the callback.
  • Do not call back into MemoryCache from the callback — this may deadlock.
  • No task queue is created; Stop() does not wait for callbacks.

Options

Option Default Description
WithBucketNum(num) 16 Number of storage buckets (auto-rounded to power of 2)
WithBucketSize(size, cap) 1000, 100000 Initial size and max capacity per bucket
WithInterval(min, max) 5s, 30s Adaptive TTL check period
WithDeleteLimits(num) 1000 Max keys deleted per TTL check per bucket
WithCachedTime(enabled) true Enable time caching for lower time.Now() overhead
WithAsyncCallback(enabled) true Dispatch callbacks asynchronously via internal queue
WithSwissTable(enabled) false Use SwissTable instead of Go runtime map

Example

package main

import (
	"fmt"
	"time"

	"github.com/lxzan/memorycache"
)

func main() {
	mc := memorycache.New[string, any](
		// Set the number of storage buckets, y=pow(2,x)
		memorycache.WithBucketNum(128),

		// Set bucket size, initial size and maximum capacity (per bucket)
		memorycache.WithBucketSize(1000, 10000),

		// Set the expiration time check period.
		// If the number of expired elements is small, take the maximum value, otherwise take the minimum value.
		memorycache.WithInterval(5*time.Second, 30*time.Second),
	)
	defer mc.Stop() // Stop background goroutines and release resources

	mc.SetWithCallback("xxx", 1, time.Second, func(element *memorycache.Element[string, any], reason memorycache.Reason) {
		fmt.Printf("callback: key=%s, reason=%v\n", element.Key, reason)
	})

	val, exist := mc.Get("xxx")
	fmt.Printf("val=%v, exist=%v\n", val, exist)

	time.Sleep(2 * time.Second)

	val, exist = mc.Get("xxx")
	fmt.Printf("val=%v, exist=%v\n", val, exist)
}

Benchmark

  • Pre-populated with 1,000,000 elements. benchtime=3s, parallel, 10 CPU cores.
goos: darwin
goarch: arm64
pkg: github.com/lxzan/memorycache/benchmark
cpu: Apple M1 Max
BenchmarkMemoryCache_Set-10           90382902        41.77 ns/op        4 B/op        0 allocs/op
BenchmarkMemoryCache_Get-10           79059558        50.51 ns/op        0 B/op        0 allocs/op
BenchmarkMemoryCache_SetAndGet-10     78810615        48.48 ns/op        0 B/op        0 allocs/op
BenchmarkMemoryCache_Delete-10       153390056        23.76 ns/op        0 B/op        0 allocs/op
BenchmarkMemoryCache_UpdateTTL-10    100000000        32.73 ns/op        0 B/op        0 allocs/op
BenchmarkRistretto_Set-10             68245581       673.1 ns/op        112 B/op        2 allocs/op
BenchmarkRistretto_Get-10             86053975        45.96 ns/op         17 B/op        1 allocs/op
BenchmarkRistretto_SetAndGet-10       27956532       110.6 ns/op         31 B/op        1 allocs/op
BenchmarkTheine_Set-10                 9754111       381.7 ns/op         22 B/op        0 allocs/op
BenchmarkTheine_Get-10                32876373       109.1 ns/op          0 B/op        0 allocs/op
BenchmarkTheine_SetAndGet-10          23014824       172.4 ns/op          0 B/op        0 allocs/op
PASS
ok      github.com/lxzan/memorycache/benchmark  103.750s

Documentation

Index

Constants

View Source
const (
	ReasonExpired = Reason(0) // 过期
	ReasonEvicted = Reason(1) // 被驱逐
	ReasonDeleted = Reason(2) // 被删除
	ReasonCleared = Reason(3) // 被清空
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CallbackFunc added in v1.1.3

type CallbackFunc[T any] func(element T, reason Reason)

type Element added in v1.1.3

type Element[K comparable, V any] struct {

	// 键
	Key K

	// 值
	Value V

	// 过期时间, 毫秒
	ExpireAt int64
	// contains filtered or unexported fields
}

type MemoryCache

type MemoryCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func New

func New[K comparable, V any](options ...Option) *MemoryCache[K, V]

New 创建缓存数据库实例 Creating a Cached Database Instance

func (*MemoryCache[K, V]) Clear added in v1.1.2

func (c *MemoryCache[K, V]) Clear()

Clear 清空缓存. 对存活非过期元素触发 ReasonCleared 回调. Clear caches. Triggers ReasonCleared callback for alive non-expired elements.

func (*MemoryCache[K, V]) Delete

func (c *MemoryCache[K, V]) Delete(key K) (exist bool)

Delete 删除缓存 delete cache

func (*MemoryCache[K, V]) Get

func (c *MemoryCache[K, V]) Get(key K) (v V, exist bool)

Get 查询缓存 query cache

func (*MemoryCache[K, V]) GetOrCreate added in v1.1.5

func (c *MemoryCache[K, V]) GetOrCreate(key K, value V, exp time.Duration) (v V, exist bool)

GetOrCreate 如果存在, 返回已有值(忽略 value 参数)并刷新过期时间. 如果不存在, 创建一个新的. Get or create a value. If it exists, returns the existing value (ignoring the value parameter) and refreshes the expiration time. If it does not exist, creates a new one.

func (*MemoryCache[K, V]) GetOrCreateWithCallback added in v1.1.5

func (c *MemoryCache[K, V]) GetOrCreateWithCallback(key K, value V, exp time.Duration, cb CallbackFunc[*Element[K, V]]) (v V, exist bool)

GetOrCreateWithCallback 如果存在, 返回已有值(忽略 value 和 cb 参数)并刷新过期时间. 如果不存在, 创建一个新的. 回调默认可通过 WithAsyncCallback 配置; 异步模式下 Element 为快照. Get or create a value with CallbackFunc. If it exists, returns the existing value (ignoring the value and cb parameters) and refreshes the expiration time. If it does not exist, creates a new one. Callback dispatch is configurable via WithAsyncCallback; in async mode the Element is a snapshot.

func (*MemoryCache[K, V]) GetTTL added in v1.2.3

func (c *MemoryCache[K, V]) GetTTL(key K) (time.Time, bool)

GetTTL 获取 key 的过期时间 Get the expiration time of the key.

func (*MemoryCache[K, V]) GetWithTTL added in v1.1.3

func (c *MemoryCache[K, V]) GetWithTTL(key K, exp time.Duration) (v V, exist bool)

GetWithTTL 获取. 如果存在, 刷新过期时间. Get a value. If it exists, refreshes the expiration time.

func (*MemoryCache[K, V]) Len

func (c *MemoryCache[K, V]) Len() int

Len 快速获取当前缓存元素数量, 不做过期检查. 注意: 返回值可能包含已过期但未清除的元素. Quickly gets the current number of cached elements, without checking for expiration. Note: the returned count may include expired elements that have not been cleaned up yet.

func (*MemoryCache[K, V]) Range added in v1.2.0

func (c *MemoryCache[K, V]) Range(f func(K, V) bool)

Range 遍历缓存 注意: 不要在回调函数里面操作 MemoryCache[K, V] 实例, 可能会造成死锁. Traverse the cache. Note: Do not manipulate MemoryCache[K, V] instances inside callback functions, as this may cause deadlocks.

func (*MemoryCache[K, V]) Set

func (c *MemoryCache[K, V]) Set(key K, value V, exp time.Duration) (exist bool)

Set 设置键值和过期时间. exp<=0表示永不过期. Set the key value and expiration time. exp<=0 means never expire.

func (*MemoryCache[K, V]) SetWithCallback added in v1.1.3

func (c *MemoryCache[K, V]) SetWithCallback(key K, value V, exp time.Duration, cb CallbackFunc[*Element[K, V]]) (exist bool)

SetWithCallback 设置键值, 过期时间和回调函数. 容量溢出和过期都会触发回调. 默认异步执行; 同步模式下回调在桶锁内执行, 收到的 Element 为活跃引用, 勿在回调中操作 MemoryCache 以免死锁. Set the key value, expiration time and callback function. Callbacks are triggered on capacity overflow or expiration. Async by default; in sync mode the callback runs under the bucket lock with a live Element reference — do not call back into MemoryCache to avoid deadlocks.

func (*MemoryCache[K, V]) Stop added in v1.1.5

func (c *MemoryCache[K, V]) Stop()

Stop 停止后台协程并排空待执行回调. Stop 之后不应再使用该实例; 若仍发生删除/清空等操作, 异步回调会降级为同步执行, 避免静默丢失. Stop background goroutines and drain pending callbacks. Do not use the instance after Stop; if mutations still occur, async callbacks fall back to synchronous execution to avoid silent loss.

func (*MemoryCache[K, V]) UpdateTTL added in v1.2.3

func (c *MemoryCache[K, V]) UpdateTTL(key K, d time.Duration) bool

UpdateTTL 更新 key 的过期时间. d<=0 表示永不过期. Update the expiration time of the key. d<=0 means never expire.

type Option added in v1.0.1

type Option func(c *config)

func WithAsyncCallback added in v1.2.3

func WithAsyncCallback(enabled bool) Option

WithAsyncCallback 是否异步执行回调, 默认为true Whether to dispatch callbacks asynchronously, true by default.

func WithBucketNum added in v1.1.0

func WithBucketNum(num int) Option

WithBucketNum 设置存储桶数量 Setting the number of storage buckets

func WithBucketSize added in v1.1.0

func WithBucketSize(size, cap int) Option

WithBucketSize 设置初始化大小和最大容量. 超过最大容量会被清除. (单个存储桶) Set the initial size and maximum capacity. Exceeding the maximum capacity will be erased. (Single bucket)

func WithCachedTime added in v1.2.0

func WithCachedTime(enabled bool) Option

WithCachedTime 是否开启时间缓存 Whether to turn on time caching

func WithDeleteLimits added in v1.2.0

func WithDeleteLimits(num int) Option

WithDeleteLimits 设置每次TTL检查最大删除key数量. (单个存储桶) Set the maximum number of keys to be deleted per TTL check (single bucket)

func WithInterval added in v1.1.0

func WithInterval(min, max time.Duration) Option

WithInterval 设置TTL检查周期 设置过期时间检查周期. 如果过期元素较少, 取最大值, 反之取最小值. Setting the TTL check period If the number of expired elements is small, take the maximum value, otherwise take the minimum value.

func WithSwissTable added in v1.2.0

func WithSwissTable(enabled bool) Option

WithSwissTable 使用swiss table替代runtime map Using swiss table instead of runtime map

type Reason added in v1.1.3

type Reason uint8

Reason 回调函数触发原因

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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