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

Go 清理模块缓存

随着模块不断升级,时间久了,`pkg` 目录越来越大,导致专门为 Linux 下编译开的虚拟机空间爆满。...

golang Selenium WebDriver 使用记录

Selenium WebDriver 直接通过浏览器自动化的本地接口来调用浏览器,以达到模拟浏览器行为的操作,如点击、选择、鼠标移动等。下面是记录个人使用golang 驱动的记录。...

groupcache 使用入门

groupcache 是 memcached 作者 Brad Fitzpatrick 用 Go 语言编写的缓存缓存过滤库,作为 memcached 许多场景下的替代版本。...

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

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