GolangNote

Golang笔记

使用 fastcache 做 go 应用缓存

Permalink

fastcache 是大牛 valyala (fasthttp 的作者)开源的一个轻量级缓存库。其优点是快速轻量、嵌入式。

fastcache 特点:

  • 快速。 性能在多核CPU上表现更好。
  • 线程安全的。 并发goroutine可以读写单个缓存实例。
  • fastcache设计用于存储大量 K/V 数据而无需GC开销。
  • Fastcache在创建期间达到设置的最大大小时会自动驱逐旧条目。
  • 可以把缓存内容导出到文件或从文件导入。
  • 简单的API。

fastcache 性能

fastcache 性能

综合读写,fastcache 是个很不错的库,可以方便作缓存。缺点是只能存储 []byte 类型。

可以对 struct 作序列化以后再保存。

下面是简单写一个可以缓存结构体与string[]byte 类型的函数:

Go: fastcache 缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func ObjCachedSet(mc *fastcache.Cache, k []byte, v interface{}) {
    switch v2 := v.(type) {
    case string:
        mc.Set(k, youdb.S2b(v2))
    case []byte:
        mc.Set(k, v2)
    default:
        if jb, err := json.Marshal(v); err == nil {
            mc.Set(k, jb)
        }
    }
}

func ObjCachedGet(mc *fastcache.Cache, k []byte, v interface{}, getByte bool) (mcValue []byte, exist bool) {
    if mcValue = mc.Get(nil, k); len(mcValue) > 0 {
        if getByte {
            exist = true
            return
        } else {
            err := json.Unmarshal(mcValue, v)
            if err == nil {
                exist = true
                return
            }
        }
    }
    return
}

调用:

Go: 调用
1
2
3
4
k := []byte("key")
v := "value"
ObjCachedSet(mc, k, v)
v, ok := ObjCachedGet(mc, k, nil, true)

传送门

https://github.com/VictoriaMetrics/fastcache

本文网址: https://golangnote.com/topic/272.html 转摘请注明来源

Related articles

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

Go Modules 使用备忘

简单说 Go Modules 就是包管理,从 go1.11 开始支持,可以不需要gopath存在,环境变量`GO111MODULE`,默认为 `auto` 项目存在 `go.mod` 则使用 go module ,否则使用GOPATH 和 vendor 机制。...

Write a Comment to "使用 fastcache 做 go 应用缓存"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms