一、介绍

bigcache是一个内存缓存零碎,用于存储键值对数据。没有gc操作。应用的时候须要序列化(反)。
bigcache的源代码在 https://github.com/allegro/bigcache

二、装置

咱们装置最新的v3版本

go get -u github.com/allegro/bigcache/v3

装置实现后,咱们就能够在go语言中应用bigcache了。上面是一些简略的示例。

三、应用示例

func TestSetGet(t *testing.T) {    // new一个bigCache对象    cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute))    // get获取一个无值的key    vNil, err := cache.Get("key")    t.Log(vNil, err) // [] Entry not found 值为空的[]字节slice    // set 存储数据    cache.Set("key", []byte("value"))    // get 获取数据    v, _ := cache.Get("key")    t.Log(v)         // 输入 [118 97 108 117 101]    t.Log(string(v)) // 输入 value}

咱们看一下 Set和Get办法的源代码

// Set saves entry under the keyfunc (c *BigCache) Set(key string, entry []byte) error {    hashedKey := c.hash.Sum64(key)    shard := c.getShard(hashedKey)    return shard.set(key, hashedKey, entry)}// Get reads entry for the key.// It returns an ErrEntryNotFound when// no entry exists for the given key.func (c *BigCache) Get(key string) ([]byte, error) {    hashedKey := c.hash.Sum64(key)    shard := c.getShard(hashedKey)    return shard.get(key, hashedKey)}

在Set()办法,存储值为 []byte 字节slice类型,所以咱们保留的时候,须要序列化数据成[]byte
而在Get()办法,获取的值为[]byte,咱们此时须要反序列化[]byte成原来的类型。

3、1 string类型的 存储与获取以及批改

func TestSetGet(t *testing.T) {    // new一个bigCache对象    cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute))    // get获取一个无值的key    vNil, err := cache.Get("key")    t.Log(vNil, err) // [] Entry not found 值为空的[]字节slice    // set 存储数据    cache.Set("key", []byte("value"))    // get 获取数据    v, _ := cache.Get("key")    t.Log(v)         // 输入 [118 97 108 117 101]    t.Log(string(v)) // 输入 value}