golang高性能无数据竞争的内存缓存插件库gocache的使用
Golang高性能无数据竞争的内存缓存插件库gocache的使用
简介
gocache是一个Go语言实现的无数据竞争的内存缓存库,为应用程序提供高效的缓存能力。
![codecov] ![CodeQL] ![Check & Build] ![License: AGPL v3] ![GitHub release (latest SemVer)]
安装
go get -u github.com/yuseferi/gocache
使用示例
下面是一个完整的gocache使用示例:
package main
import (
"fmt"
"time"
"github.com/yuseferi/gocache"
)
func main() {
// 创建一个每2分钟清理过期项的缓存
cache := gocache.NewCache(time.Minute * 2)
// 设置缓存项,有效期1分钟
cache.Set("username", "john_doe", time.Minute)
cache.Set("user_id", 12345, time.Minute*5)
// 获取缓存值
if value, found := cache.Get("username"); found {
fmt.Printf("Username: %v\n", value) // 输出: Username: john_doe
}
// 获取不存在的键
if _, found := cache.Get("nonexistent"); !found {
fmt.Println("Key 'nonexistent' not found")
}
// 删除特定键
cache.Delete("username")
// 获取当前缓存大小
size := cache.Size()
fmt.Printf("Current cache size: %d\n", size)
// 清空所有缓存项
cache.Clear()
// 再次获取大小
size = cache.Size()
fmt.Printf("Cache size after clear: %d\n", size)
}
主要功能
- 创建缓存:
// 创建一个每2分钟清理过期项的缓存
cache := gocache.NewCache(time.Minute * 2)
- 设置缓存项:
// 设置缓存项,key为"key",value为"value",有效期1分钟
cache.Set("key", "value", time.Minute)
- 获取缓存值:
// 获取缓存值,found表示是否找到
value, found := cache.Get("key")
- 删除缓存项:
// 删除特定键
cache.Delete("key")
- 清空缓存:
// 清空所有缓存项
cache.Clear()
- 获取缓存大小:
// 获取当前缓存中项的数量
size := cache.Size()
贡献
我们坚信开源的力量❤️😊。欢迎通过提出问题或提交拉取请求来贡献代码,使gocache变得更好!
本项目采用GNU GENERAL PUBLIC LICENSE许可证发布。
更多关于golang高性能无数据竞争的内存缓存插件库gocache的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于golang高性能无数据竞争的内存缓存插件库gocache的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
GoCache - 高性能无数据竞争的Go内存缓存库
GoCache是一个高性能、线程安全的内存缓存库,适用于Go应用程序。它提供了多种缓存策略和特性,可以帮助你构建高效的无数据竞争缓存系统。
主要特性
- 线程安全,无数据竞争
- 支持多种缓存策略:LRU、LFU、ARC等
- 支持过期时间设置
- 高性能,低延迟
- 简单易用的API
安装
go get github.com/eko/gocache/v3
基本使用示例
1. 简单缓存
package main
import (
"fmt"
"time"
"github.com/eko/gocache/v3/cache"
"github.com/eko/gocache/v3/store"
)
func main() {
// 初始化缓存存储(这里使用内存存储)
cacheStore := store.NewInMemoryStore()
// 创建缓存管理器
cacheManager := cache.New(cacheStore)
// 设置缓存
err := cacheManager.Set("my-key", "my-value", &store.Options{
Expiration: 5 * time.Second, // 5秒后过期
})
if err != nil {
panic(err)
}
// 获取缓存
value, err := cacheManager.Get("my-key")
if err != nil {
panic(err)
}
fmt.Printf("Value: %v\n", value)
// 等待过期
time.Sleep(6 * time.Second)
// 再次获取(应该已过期)
_, err = cacheManager.Get("my-key")
if err != nil {
fmt.Println("Key has expired:", err)
}
}
2. 使用LRU策略
package main
import (
"fmt"
"github.com/eko/gocache/v3/cache"
"github.com/eko/gocache/v3/store"
)
func main() {
// 创建LRU存储,最大1000个项目
lruStore := store.NewLRU(1000)
// 创建缓存管理器
cacheManager := cache.New(lruStore)
// 设置多个缓存项
for i := 0; i < 1500; i++ {
key := fmt.Sprintf("key-%d", i)
value := fmt.Sprintf("value-%d", i)
cacheManager.Set(key, value, nil)
}
// 检查最早的项目是否被淘汰
_, err := cacheManager.Get("key-0")
if err != nil {
fmt.Println("key-0 has been evicted by LRU policy")
}
}
3. 高级用法 - 多级缓存
package main
import (
"fmt"
"time"
"github.com/eko/gocache/v3/cache"
"github.com/eko/gocache/v3/marshaler"
"github.com/eko/gocache/v3/store"
)
type User struct {
ID int
Name string
}
func main() {
// 创建内存存储
memoryStore := store.NewInMemoryStore()
// 创建缓存管理器
cacheManager := cache.New(memoryStore)
// 使用Marshaler简化复杂类型的存储
marshal := marshaler.New(cacheManager)
// 存储结构体
user := &User{ID: 1, Name: "John Doe"}
err := marshal.Set("user-1", user, &store.Options{
Expiration: 10 * time.Minute,
})
if err != nil {
panic(err)
}
// 获取结构体
var retrievedUser User
err = marshal.Get("user-1", &retrievedUser)
if err != nil {
panic(err)
}
fmt.Printf("Retrieved user: %+v\n", retrievedUser)
}
4. 使用指标监控缓存
package main
import (
"fmt"
"time"
"github.com/eko/gocache/v3/cache"
"github.com/eko/gocache/v3/metrics"
"github.com/eko/gocache/v3/store"
)
func main() {
// 创建内存存储
cacheStore := store.NewInMemoryStore()
// 创建带指标的缓存
metricsStore := metrics.NewPrometheus("my_app")
cacheManager := cache.NewMetric(metricsStore, cache.New(cacheStore))
// 模拟一些缓存操作
for i := 0; i < 100; i++ {
key := fmt.Sprintf("key-%d", i)
value := fmt.Sprintf("value-%d", i)
// 设置缓存
cacheManager.Set(key, value, &store.Options{
Expiration: time.Minute,
})
// 获取缓存
_, _ = cacheManager.Get(key)
// 删除部分缓存
if i%10 == 0 {
_ = cacheManager.Delete(key)
}
}
// 指标可以通过Prometheus端点获取
fmt.Println("Cache metrics are available at /metrics")
}
性能优化建议
- 批量操作:尽可能使用批量操作减少锁竞争
- 适当大小:根据应用场景调整缓存大小
- 合理过期:设置合理的过期时间避免内存泄漏
- 监控:使用内置指标监控缓存命中率等关键指标
- 避免大对象:大对象会增加GC压力
与其他库的比较
- 相比
sync.Map
:GoCache提供了更丰富的缓存特性和策略 - 相比
bigcache
:GoCache更灵活,支持多种存储后端 - 相比
groupcache
:GoCache更轻量,更适合单机缓存
GoCache是一个功能全面且高性能的内存缓存解决方案,适合大多数Go应用程序的缓存需求。