go-cache基本介绍

go-cache 是一个轻量级的基于内存的 key:value 储存组件,类似于memcached,适用于在单机上运行的应用程序。它的主要优点是,本质上是一个具有过期时间的线程安全map[string]interface{}。interface的结构决定了它不需要序列化。基于内存的特性决定了其不需要网络传输其内容,因此就不存在网络耗时。

主要具备如下功能:
线程安全,多 goroutine 并发安全访问;
每个 item 可以单独设置过期时间(或无过期时间);
自动定期清理过期的 item;
可以自定义清理回调函数;
支持将缓存数据保存到文件,并从文件中恢复数据到内存。

项目地址:

https://github.com/patrickmn/go-cache

文档地址:

http://godoc.org/github.com/patrickmn/go-cache

代码中import引入路径

import "github.com/patrickmn/go-cache"

基本使用

直接上代码

package main

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

func main() {
    // 初始化cache 默认过期时间设置为5*time.Minute,扫描过期key的间隔时间10*time.Minute
    c := cache.New(5*time.Minute, 10*time.Minute)

    // 设置为默认过期时间,即New时设置的时间5*time.Minute
    c.Set("foo", "bar", cache.DefaultExpiration)

    // 设置为不过期
    c.Set("baz", 42, cache.NoExpiration)

    // 设置指定过期时间为100秒
    c.Set("cache", 100, time.Second*3)

    // Get the string associated with the key "foo" from the cache
    foo, found := c.Get("foo")
    if found {
        fmt.Println(foo)
    }

    // 验证过期
    <-time.After(5 * time.Second)
    cacheRes, found := c.Get("cache")
    if found {
        fmt.Println(cacheRes)
    } else {
        fmt.Println("cache not found")
    }

    // 因为value是interface{}类型,所以如果需要存入的类型,需要断言
    var fooValue string
    if x, ok := c.Get("foo"); ok {
        fooValue = x.(string)
    }
    fmt.Println("fooValue:", fooValue)

    //对于结构体,存储一个指针,可以有一个更好的性能
    c.Set("MyStruct", &MyStruct{
        Name: "gary",
        Age:  18,
    }, cache.DefaultExpiration)
    if x, ok := c.Get("MyStruct"); ok {
        res := x.(*MyStruct)
        fmt.Println("MyStruct:", res)
    }

    // 删除key
    c.Delete("foo")
    if fooRes, ok := c.Get("foo"); ok {
        fmt.Println("after delete", fooRes)
    } else {
        fmt.Println("after delete not found foo")
    }
}

type MyStruct struct {
    Name string
    Age  int
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容