golang一个轻量级基于内存的kv存储或缓存

golang一个轻量级基于内存的kv存储或缓存

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

在使用时,一般都是将go-cache作为数据缓存来使用,而不是持久性的数据存储。对于停机后快速恢复的场景,go-cache支持将缓存数据保存到文件,恢复时从文件中load数据加载到内存。

go-cache广泛使用在go语言编程中,适合在单机上存储键值对形式的内存缓存。

github上地址为: https://github.com/patrickmn/go-cache

它在并发的时候,线程安全(读写锁) + map[string]interface{} + 过期时间 来作为go的本地化存储。

这也是他的三大特性:

  • 线程安全,通过读写锁支持多个协程并发访问
  • 不需要序列化,键值对形式,任意值类型map[string]interface{}
  • 自定义每个key的过期时间

cache基本使用

安装go-cache

go get github.com/patrickmn/go-cache

创建一个go文件,例如:cache_demo.go 内容如下

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
}

cache封装

项目中定义一个cache包,所有缓存方法封装到cache包里,外部直接调用

package cache

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

var c *cache.Cache

func init() {
	//创建一个默认过期时间为5分钟的缓存,并且
	//每10分钟清除一次过期项目
	c = cache.New(5*time.Minute, 10*time.Minute)
}

// 缓存保存 默认的过期时间
func SetDefaultExpire(key string, value interface{}) {
	c.Set(key, value, cache.DefaultExpiration)
}

// 缓存放入 不过期
func SetNoExpire(key string, value interface{}) {
	c.Set(key, value, cache.NoExpiration)
}

// 缓存放入 设置过期时间
func SetExpire(key string, value interface{}, t time.Duration) {
	c.Set(key, value, t)
}

// 缓存获取
func Get(key string) (interface{}, bool) {
	return c.Get(key)
}

// 删除缓存
func Delete(key string) {
	c.Delete(key)
}


参考链接:
https://github.com/patrickmn/go-cache
https://www.jianshu.com/p/1ba4d429d3d3
https://www.cnblogs.com/Moon-Light-Dream/p/12494683.html

你可能感兴趣的:(golang,golang,缓存,开发语言)