golang库收集

3 阅读1分钟

go-cache

链接

简介

go-cache是一个存储在内存中的键值对,类似于memcached,适用于在单台机器上运行的应用程序。本质上是一个有过期时间的、线程安全的map[string]interface,因此可以直接通过内存指针访问数据,而不需要序列化&网络传输。

任何对象都可以在给定时长(或永久)内存储,并可以由多个goroutine安全使用。虽然go-cache并非为持久化存储设计,但通过将整个缓存保存到文件,或从文件中加载,可以快速从服务中断中恢复。

代码示例

import (
	"fmt"
	"github.com/patrickmn/go-cache"
	"time"
)

func main() {
	// 创建缓存实例,过期时长5分钟,销毁时长10分钟
	c := cache.New(5*time.Minute, 10*time.Minute)

	// 将键"foo"的值设置为“bar”,并使用默认过期时长
	c.Set("foo", "bar", cache.DefaultExpiration)

	// 将键"baz"的值设置为42,并不设置过期时长。可重新设置或c.Delete("baz")删除
	c.Set("baz", 42, cache.NoExpiration)

	// 从缓存中获取与键“foo”关联的字符串
	foo, found := c.Get("foo")
	if found {
		fmt.Println(foo)
	}

	// 当值被传递给不采用任意类型的函数(即接口{})时,需要类型断言
	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)
			// ...
	}
}