cache

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2025 License: MIT Imports: 11 Imported by: 0

README

高性能分片缓存

这个缓存实现提供了高性能、线程安全的内存缓存系统,支持普通键值对缓存和列表操作。主要特性包括:

优化特性

  1. 分片设计

    • 默认使用多个分片存储数据,减少锁争用
    • 自动根据CPU核心数量调整分片数,可手动配置
    • 使用高效哈希算法将键分散到不同分片
  2. 并发性能

    • 读操作性能提升36%(与传统单一锁实现相比)
    • 使用读写锁分离读写操作
    • 采用细粒度锁,不同键的操作可并行执行
  3. 资源优化

    • 内存分配减少50%,每操作平均1个分配
    • 阻塞操作使用通知机制替代轮询,减少CPU消耗
    • 延迟删除和分批处理过期项避免全局锁
  4. 持久化改进

    • 异步持久化减少阻塞
    • 仅保存未过期数据减少磁盘占用
    • 原子写入保证数据一致性

基准测试结果

操作类型 优化前(ns/op) 优化后(ns/op) 性能提升 内存分配减少
并发读取 1156 742 36% 相同
并发写入 1061 1003 5% 50%
混合操作 600 741 -19% 50%

注意:混合操作场景中性能略有下降,这是因为实现了更复杂的功能(过期时间、通知机制等),但内存分配减少了一半。

使用示例

// 创建带16个分片的缓存
cache := NewCache[string, int](5*time.Minute, 1*time.Minute, 16)

// 设置值
cache.Set("key1", 100)                 // 使用默认过期时间
cache.Set("key2", 200, 10*time.Second) // 指定过期时间

// 获取值
value, found := cache.Get("key1")

// 列表操作
cache.LPush("list1", 1, 2, 3)  // 添加到列表头部
cache.RPush("list1", 4, 5)     // 添加到列表尾部
value, _ = cache.LPop("list1") // 弹出列表头部元素

// 阻塞操作
value, found = cache.BLPop("list1", 5*time.Second) // 最多等待5秒

// 持久化
cache.WithPersistence("cache.dat", 1*time.Minute)
cache.EnableAutoPersist() // 启用自动持久化
cache.Save()             // 手动保存
cache.Load()             // 手动加载

注意事项

  1. 分片数量建议设置为CPU核心数的1-4倍
  2. 在极高并发下可能会有哈希冲突,考虑增加分片数
  3. 对同一个键的频繁读写会导致性能下降,因为它们会争用同一分片的锁

Documentation

Index

Constants

View Source
const (
	// DefaultHistorySize 默认历史记录大小
	DefaultHistorySize = 50
	// DefaultBufferSize 默认缓存缓冲区大小
	DefaultBufferSize = 512
	// DefaultShardCount 默认分片数量,设为CPU数量的2倍提高并发性
	DefaultShardCount = 16
	// DefaultCleanupInterval 默认清理过期数据的间隔
	DefaultCleanupInterval = 5 * time.Minute
	// DefaultItemsPerCleanup 每次清理处理的最大项目数,避免长时间锁定
	DefaultItemsPerCleanup = 1000
)

添加分片常量和条件变量相关定义

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache 是一个综合的缓存实现,支持内存缓存和列表缓存

func New added in v0.1.5

func New[K comparable, V any](config Config) *Cache[K, V]

New 使用配置创建缓存实例

func NewCache

func NewCache[K comparable, V any](defaultExpiration, cleanupInterval time.Duration, options ...int) *Cache[K, V]

NewCache 创建一个新的综合缓存 defaultExpiration: 默认的过期时间 cleanupInterval: 清理过期项的间隔时间 可选的shardCount: 分片数量,默认为CPU核心数*2

func NewCacheWithPersistence

func NewCacheWithPersistence[K comparable, V any](defaultExpiration, cleanupInterval time.Duration, persistPath string, autoPersistInterval time.Duration) *Cache[K, V]

NewCacheWithPersistence 初始化带持久化的全局缓存

func (*Cache[K, V]) AddToListWithLimit added in v0.1.5

func (c *Cache[K, V]) AddToListWithLimit(key K, value V, maxSize int)

AddToListWithLimit 将元素添加到列表,并在超出限制时修剪列表

func (*Cache[K, V]) BLPop

func (c *Cache[K, V]) BLPop(key K, timeout time.Duration) (V, bool)

BLPop 阻塞版本的LPop,使用通知机制代替轮询 timeout为等待时间,0表示无限等待

func (*Cache[K, V]) BRPop

func (c *Cache[K, V]) BRPop(key K, timeout time.Duration) (V, bool)

BRPop 阻塞版本的RPop,使用通知机制代替轮询 timeout为等待时间,0表示无限等待

func (*Cache[K, V]) BRPopLPush

func (c *Cache[K, V]) BRPopLPush(source K, destination K, timeout time.Duration) (V, bool)

BRPopLPush 阻塞版本的RPoplPush,使用通知机制代替轮询 timeout为等待时间,0表示无限等待

func (*Cache[K, V]) BeginTransaction

func (c *Cache[K, V]) BeginTransaction() *Transaction[K, V]

BeginTransaction 开始一个新事务

func (*Cache[K, V]) Clear

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

Clear 清空缓存

func (*Cache[K, V]) Close

func (c *Cache[K, V]) Close()

Close 停止清理过期项和自动持久化的goroutine

func (*Cache[K, V]) Count

func (c *Cache[K, V]) Count() int

Count 返回缓存中的普通项目数量

func (*Cache[K, V]) Delete

func (c *Cache[K, V]) Delete(key K)

Delete 删除缓存项

func (*Cache[K, V]) DeleteExpired

func (c *Cache[K, V]) DeleteExpired()

DeleteExpired 删除所有过期的项 采用分片清理策略减少锁争用,每次只清理部分数据

func (*Cache[K, V]) DeleteList

func (c *Cache[K, V]) DeleteList(key K)

DeleteList 删除列表

func (*Cache[K, V]) DisableAutoPersist

func (c *Cache[K, V]) DisableAutoPersist()

DisableAutoPersist 禁用自动持久化

func (*Cache[K, V]) EnableAutoPersist

func (c *Cache[K, V]) EnableAutoPersist()

EnableAutoPersist 启用自动持久化

func (*Cache[K, V]) Flush

func (c *Cache[K, V]) Flush() error

Flush 清除所有数据并删除持久化文件

func (*Cache[K, V]) ForEach

func (c *Cache[K, V]) ForEach(fn func(key K, value V) bool)

ForEach 遍历所有未过期的缓存项并对每一项执行指定的函数 优化为分片遍历,减少锁争用

func (*Cache[K, V]) ForEachList

func (c *Cache[K, V]) ForEachList(fn func(key K, list []V) bool)

ForEachList 遍历所有未过期的列表

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(key K) (V, bool)

Get 获取缓存项

func (*Cache[K, V]) GetListTTL

func (c *Cache[K, V]) GetListTTL(key K) (time.Duration, bool)

GetListTTL 获取列表键的剩余生存时间

func (*Cache[K, V]) GetStats

func (c *Cache[K, V]) GetStats() Stats

GetStats 获取缓存统计信息

func (*Cache[K, V]) GetTTL

func (c *Cache[K, V]) GetTTL(key K) (time.Duration, bool)

GetTTL 获取键的剩余生存时间

func (*Cache[K, V]) GetWithTTL

func (c *Cache[K, V]) GetWithTTL(key K) (V, time.Duration, bool)

GetWithTTL 获取缓存项及其剩余生存时间

func (*Cache[K, V]) Has

func (c *Cache[K, V]) Has(key K) bool

Has 检查键是否存在且未过期

func (*Cache[K, V]) HasList

func (c *Cache[K, V]) HasList(key K) bool

HasList 检查列表键是否存在且未过期

func (*Cache[K, V]) Increment

func (c *Cache[K, V]) Increment(key K, increment any) (any, error)

Increment 对数值类型进行增加操作

func (*Cache[K, V]) Keys

func (c *Cache[K, V]) Keys() []K

Keys 返回所有的普通缓存键

func (*Cache[K, V]) LIndex

func (c *Cache[K, V]) LIndex(key K, index int) (V, bool)

LIndex 通过索引获取列表中的元素

func (*Cache[K, V]) LInsert

func (c *Cache[K, V]) LInsert(key K, before bool, pivot V, value V, equals func(a, b V) bool) int

LInsert 在列表的指定位置插入元素 before == true表示在pivot之前插入 before == false表示在pivot之后插入

func (*Cache[K, V]) LLen

func (c *Cache[K, V]) LLen(key K) int

LLen 获取列表长度

func (*Cache[K, V]) LPop

func (c *Cache[K, V]) LPop(key K) (V, bool)

LPop 移除并返回列表头部的元素

func (*Cache[K, V]) LPush

func (c *Cache[K, V]) LPush(key K, values ...V) int

LPush 将一个或多个值插入到列表头部

func (*Cache[K, V]) LRange

func (c *Cache[K, V]) LRange(key K, start, stop int) []V

LRange 获取列表指定范围内的元素

func (*Cache[K, V]) LRem

func (c *Cache[K, V]) LRem(key K, count int, value V, equals func(a, b V) bool) int

LRem 移除列表中与参数value相等的元素 count > 0: 从头往尾移除count个值为value的元素 count < 0: 从尾往头移除count个值为value的元素 count = 0: 移除所有值为value的元素

func (*Cache[K, V]) LSet

func (c *Cache[K, V]) LSet(key K, index int, value V) bool

LSet 通过索引来设置列表元素的值

func (*Cache[K, V]) LTrim

func (c *Cache[K, V]) LTrim(key K, start, stop int) bool

LTrim 对一个列表进行修剪,只保留指定区间内的元素

func (*Cache[K, V]) ListCount

func (c *Cache[K, V]) ListCount() int

ListCount 返回列表数量

func (*Cache[K, V]) ListKeys

func (c *Cache[K, V]) ListKeys() []K

ListKeys 返回所有的列表键

func (*Cache[K, V]) Load

func (c *Cache[K, V]) Load() error

Load 从文件加载缓存

func (*Cache[K, V]) LoadOrInit

func (c *Cache[K, V]) LoadOrInit() error

LoadOrInit 从文件加载缓存,如果文件不存在则初始化一个新的缓存

func (*Cache[K, V]) RPop

func (c *Cache[K, V]) RPop(key K) (V, bool)

RPop 移除并返回列表尾部的元素

func (*Cache[K, V]) RPoplPush

func (c *Cache[K, V]) RPoplPush(source K, destination K) (V, bool)

RPoplPush 移除列表的最后一个元素,并将该元素添加到另一个列表的头部并返回它

func (*Cache[K, V]) RPush

func (c *Cache[K, V]) RPush(key K, values ...V) int

RPush 将一个或多个值插入到列表尾部

func (*Cache[K, V]) Save

func (c *Cache[K, V]) Save() error

Save 保存缓存到文件,优化锁策略

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(key K, value V, duration ...time.Duration)

Set 设置缓存项,可选过期时间。不传递过期时间时使用默认过期时间

func (*Cache[K, V]) SetList

func (c *Cache[K, V]) SetList(key K, duration ...time.Duration)

SetList 设置列表的过期时间,不传递过期时间时使用默认过期时间

func (*Cache[K, V]) WithPersistence

func (c *Cache[K, V]) WithPersistence(persistPath string, autoPersistInterval time.Duration) *Cache[K, V]

WithPersistence 配置持久化选项

type CacheItem

type CacheItem[T any] struct {
	Value      T
	Expiration int64 // Unix时间戳,表示过期时间
}

CacheItem 表示缓存中的一个项目

type Config added in v0.1.5

type Config struct {
	// TTL 默认过期时间
	TTL time.Duration
	// CleanupInterval 清理过期项的间隔
	CleanupInterval time.Duration
	// ShardCount 分片数量(可选)
	ShardCount int
	// PersistPath 持久化文件路径(可选)
	PersistPath string
	// AutoPersistInterval 自动持久化间隔(可选)
	AutoPersistInterval time.Duration
}

Config 缓存配置

func DefaultConfig added in v0.1.5

func DefaultConfig() *Config

DefaultConfig 返回默认配置

type ListItem

type ListItem[T any] struct {
	Value T
}

ListItem 表示列表中的一个项目

type PersistenceData

type PersistenceData[K comparable, V any] struct {
	Items             map[K]CacheItem[V]
	ListItems         map[K][]ListItem[V]
	Expiration        map[K]int64
	DefaultExpiration time.Duration
}

PersistenceData 持久化数据结构

type Shard added in v0.1.5

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

Shard 表示缓存的一个分片

type Stats

type Stats struct {
	ItemsCount    int           `json:"itemsCount"`    // 普通缓存项数量
	ListsCount    int           `json:"listsCount"`    // 列表数量
	HitCount      uint64        `json:"hitCount"`      // 命中次数
	MissCount     uint64        `json:"missCount"`     // 未命中次数
	LastSaveTime  time.Time     `json:"lastSaveTime"`  // 最后一次保存时间
	LastLoadTime  time.Time     `json:"lastLoadTime"`  // 最后一次加载时间
	CreationTime  time.Time     `json:"creationTime"`  // 创建时间
	MemoryUsage   uint64        `json:"memoryUsage"`   // 预估内存使用(字节)
	ExpiredCount  uint64        `json:"expiredCount"`  // 过期项目计数
	DeletedCount  uint64        `json:"deletedCount"`  // 删除项目计数
	PersistPath   string        `json:"persistPath"`   // 持久化路径
	IsAutoPersist bool          `json:"isAutoPersist"` // 是否开启自动持久化
	SaveInterval  time.Duration `json:"saveInterval"`  // 保存间隔
}

Stats 缓存统计信息

type Transaction

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

Transaction 表示一个缓存事务

func (*Transaction[K, V]) Commit

func (t *Transaction[K, V]) Commit()

Commit 提交事务

func (*Transaction[K, V]) Delete

func (t *Transaction[K, V]) Delete(key K)

Delete 在事务中删除缓存项

func (*Transaction[K, V]) DeleteList

func (t *Transaction[K, V]) DeleteList(key K)

DeleteList 在事务中删除列表

func (*Transaction[K, V]) LPush

func (t *Transaction[K, V]) LPush(key K, values ...V)

LPush 在事务中将值插入列表头部

func (*Transaction[K, V]) Rollback

func (t *Transaction[K, V]) Rollback()

Rollback 回滚事务(什么也不做,因为事务只在Commit时才会应用)

func (*Transaction[K, V]) Set

func (t *Transaction[K, V]) Set(key K, value V, duration time.Duration)

Set 在事务中设置缓存项

func (*Transaction[K, V]) SetListExpiration

func (t *Transaction[K, V]) SetListExpiration(key K, duration time.Duration)

SetListExpiration 在事务中设置列表过期时间

Jump to

Keyboard shortcuts

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