patrickmn/go-cache
GitHub: patrickmn/go-cache
一个轻量级的 Go 内存键值缓存库,提供线程安全的本地缓存能力,支持 TTL 过期策略,适合单机应用。
Stars: 8837 | Forks: 906
# go-cache
go-cache 是一个内存中的 key:value 存储/缓存,类似于 memcached,适用于在单机上运行的应用程序。它的主要优点在于,它本质上是一个带有过期时间的、线程安全的 `map[string]interface{}`,因此不需要将其内容序列化或通过网络传输。
任何对象都可以被存储一段指定的时间或永久存储,并且该缓存可以安全地被多个 goroutine 使用。
虽然 go-cache 并不打算被用作持久化数据存储,但整个缓存可以被保存到文件中并从中加载(使用 `c.Items()` 检索 item map 进行序列化,并使用 `NewFrom()` 从反序列化的数据创建缓存),以便从停机状态中快速恢复。(有关注意事项,请参阅 `NewFrom()` 的文档。)
### 安装
`go get github.com/patrickmn/go-cache`
### 用法
```
import (
"fmt"
"github.com/patrickmn/go-cache"
"time"
)
func main() {
// Create a cache with a default expiration time of 5 minutes, and which
// purges expired items every 10 minutes
c := cache.New(5*time.Minute, 10*time.Minute)
// Set the value of the key "foo" to "bar", with the default expiration time
c.Set("foo", "bar", cache.DefaultExpiration)
// Set the value of the key "baz" to 42, with no expiration time
// (the item won't be removed until it is re-set, or removed using
// c.Delete("baz")
c.Set("baz", 42, cache.NoExpiration)
// Get the string associated with the key "foo" from the cache
foo, found := c.Get("foo")
if found {
fmt.Println(foo)
}
// Since Go is statically typed, and cache values can be anything, type
// assertion is needed when values are being passed to functions that don't
// take arbitrary types, (i.e. interface{}). The simplest way to do this for
// values which will only be used once--e.g. for passing to another
// function--is:
foo, found := c.Get("foo")
if found {
MyFunction(foo.(string))
}
// This gets tedious if the value is used several times in the same function.
// You might do either of the following instead:
if x, found := c.Get("foo"); found {
foo := x.(string)
// ...
}
// or
var foo string
if x, found := c.Get("foo"); found {
foo = x.(string)
}
// ...
// foo can then be passed around freely as a string
// Want performance? Store pointers!
c.Set("foo", &MyStruct, cache.DefaultExpiration)
if x, found := c.Get("foo"); found {
foo := x.(*MyStruct)
// ...
}
}
```
### 参考
`godoc` 或 [http://godoc.org/github.com/patrickmn/go-cache](http://godoc.org/github.com/patrickmn/go-cache)
标签:EVTX分析, Go, Ruby工具, 内存数据库, 开发组件, 日志审计, 缓存, 键值存储