虽然go-cache 不打算用作持久数据存储,但是可以将整个缓存数据保存到文件(或任何io.reader/writer)中,并且能快速从中指定数据源加载,快速恢复状态。
demo
package mainimport ( "log" "time" "github.com/patrickmn/go-cache")func main(){ c := cache.new(30*time.second, 10*time.second) c.set("title", "spring festival", cache.defaultexpiration) value, found := c.get("title") if found { log.println("found:", value) } else { log.println("not found") } time.sleep(60*time.second) log.println("sleep 60s...") value, found = c.get("title") if found { log.println("found:", value) } else { log.println("not found") }}
output
2019/02/05 17:49:32 found: spring festival2019/02/05 17:50:32 sleep 60s…2019/02/05 17:50:32 not found
首先,创建一个新的cache,其中的key过期时间是30s,并且每10s清除缓存中的过期key。
定期清除缓存中的过期key,是通过一个常驻goroutine实现的。
接着,设置一个key/value,及其过期时间。过期时间使用默认过期时间,即30s。
获取这个key,可以看到,此时这个key在cache中是存在的。
睡眠60s,使刚才设置的key过期。
再次获取这个key,此时key已经过期,被清除了,不在cache
以上就是golang-cache是全局吗的详细内容。
