golang实现内存键值存储并支持TTL过期机制的插件库ttlcache的使用
golang实现内存键值存储并支持TTL过期机制的插件库ttlcache的使用
关于ttlcache
ttlcache 是一个简单高效的内存键值存储库,每个记录都支持TTL过期机制。
键的类型是uint64。库提供了常见类型的包装器:
- IntKey
- ByteKey
- Int8Key
- Uint8Key
- Int16Key
- Uint16Key
- Int32Key
- Uint32Key
- Int64Key
- Uint64Key
- BytesKey ([]byte)
- StringKey
- AnyKey (interface{})
AnyKey
不适合非常密集的使用。如果你的键是复杂类型并且遇到性能问题,可以考虑编写自己的哈希函数。
安装
go get -u github.com/cheshir/ttlcache
使用示例
package main
import (
"fmt"
"time"
"github.com/cheshir/ttlcache"
)
const (
minute = 60 * time.Second
hour = 60 * minute
)
func main() {
// 设置清理过期记录的频率
resolution := minute
// 创建新的缓存实例
cache := ttlcache.New(resolution)
// 设置键值对,并指定TTL为1小时
cache.Set(ttlcache.StringKey("some key"), "value", hour)
// 获取值
value, ok := cache.Get(ttlcache.StringKey("some key"))
if !ok {
// 缓存中没有该键的记录,可能已过期
fmt.Println("Key not found or expired")
return
}
// 需要进行类型断言,因为返回的值是interface{}类型
fmt.Println(value.(string)) // 输出: value
}
性能
如果你对性能基准测试感兴趣,可以在仓库中查看。只需调整数字和类型,检查该库是否适合你的用途。
go test -bench=. -benchmem
以下是基准测试结果(MacBook Pro 16"):
BenchmarkCache_Set_100-16 8959221 125 ns/op
BenchmarkCache_Set_1000-16 9177854 123 ns/op
BenchmarkCache_Set_10000-16 9247304 131 ns/op
BenchmarkCache_Get_100-16 50562800 23.9 ns/op
BenchmarkCache_Get_1000-16 47270793 26.9 ns/op
BenchmarkCache_Get_10000-16 42578484 27.7 ns/op
这个库提供了高效的内存键值存储功能,并支持TTL过期机制,非常适合需要缓存功能的Go应用程序。
更多关于golang实现内存键值存储并支持TTL过期机制的插件库ttlcache的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang实现内存键值存储并支持TTL过期机制的插件库ttlcache的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang 内存键值存储与 TTL 过期机制 - ttlcache 使用指南
ttlcache 是一个流行的 Golang 内存键值存储库,支持自动过期机制。下面我将详细介绍如何使用这个库。
安装
首先安装 ttlcache 库:
go get github.com/ReneKroon/ttlcache/v3
基本使用
1. 创建缓存实例
package main
import (
"fmt"
"time"
"github.com/ReneKroon/ttlcache/v3"
)
func main() {
// 创建缓存实例,设置默认TTL为5秒
cache := ttlcache.New(
ttlcache.WithTTL[string, string](5 * time.Second),
)
// 启动自动清理过期项目的goroutine
go cache.Start()
// 使用完毕后关闭
defer cache.Stop()
}
2. 设置和获取值
// 设置值
cache.Set("key1", "value1", ttlcache.DefaultTTL)
cache.Set("key2", "value2", 10*time.Second) // 自定义TTL
// 获取值
if value := cache.Get("key1"); value != nil {
fmt.Println("Found value:", value.Value())
} else {
fmt.Println("Value not found or expired")
}
高级功能
1. 设置回调函数
cache := ttlcache.New(
ttlcache.WithTTL[string, int](time.Minute),
ttlcache.WithOnEviction(func(key string, value ttlcache.EvictionReason, v int) {
fmt.Printf("Key %s evicted due to %s\n", key, value)
}),
)
2. 检查项目是否存在
if item := cache.Get("key1"); item != nil && !item.IsExpired() {
// 项目存在且未过期
}
3. 删除项目
cache.Delete("key1")
4. 遍历所有项目
for item := range cache.Items() {
fmt.Printf("Key: %s, Value: %v, Expires at: %v\n",
item.Key(), item.Value(), item.ExpiresAt())
}
完整示例
package main
import (
"fmt"
"time"
"github.com/ReneKroon/ttlcache/v3"
)
func main() {
// 创建缓存,默认TTL为3秒
cache := ttlcache.New(
ttlcache.WithTTL[string, string](3 * time.Second),
ttlcache.WithOnEviction(func(key string, reason ttlcache.EvictionReason, value string) {
fmt.Printf("Key '%s' evicted: %s (value was '%s')\n", key, reason, value)
}),
)
go cache.Start()
defer cache.Stop()
// 设置几个值
cache.Set("greeting", "Hello, World!", ttlcache.DefaultTTL)
cache.Set("name", "Alice", 5*time.Second) // 自定义TTL
// 获取并打印值
if item := cache.Get("greeting"); item != nil {
fmt.Println("Greeting:", item.Value())
}
// 等待4秒后检查
time.Sleep(4 * time.Second)
fmt.Println("\nAfter 4 seconds:")
fmt.Println("Greeting:", cache.Get("greeting")) // 应该已过期
fmt.Println("Name:", cache.Get("name")) // 应该还在
// 等待2秒后再次检查
time.Sleep(2 * time.Second)
fmt.Println("\nAfter 6 seconds:")
fmt.Println("Name:", cache.Get("name")) // 应该已过期
}
性能考虑
- ttlcache 使用读写锁保证并发安全
- 自动清理是定期执行的,默认间隔为1秒
- 对于高频访问场景,可以考虑调整清理间隔:
cache := ttlcache.New(
ttlcache.WithTTL[string, int](time.Minute),
ttlcache.WithCleanUpInterval(500 * time.Millisecond), // 更频繁的清理
)
ttlcache 是一个轻量级但功能完善的缓存解决方案,适合需要内存缓存并支持自动过期的场景。对于更复杂的需求,还可以考虑其他库如 go-cache 或 groupcache。