youbbs
youbbs
9707 0 0

fastcache:牛人又出新品,线程安全的内存缓存

这是个快速的缓存库,接口很简单,代码清晰易读

func New(maxBytes int) *Cache
func (c *Cache) Del(k []byte)
func (c *Cache) Get(dst, k []byte) []byte
func (c *Cache) Reset()
func (c *Cache) Set(k, v []byte)
func (c *Cache) UpdateStats(s *Stats)

特点:

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

其主要开发者 valyala 三年前开发的 fasthttp 比标准库http 快10倍,同时也发布了一系列fast* 库,
参见 https://www.youbbs.org/t/1966

性能:与 BigCache、标准库sync.Map 比较

限制:

  • 键和值必须是byte slice
  • key/value不能超过64KB,(更新:超过64KB的数据可用 SetBig/GetBig 存取)
  • 没有缓存过期,满了会删掉旧的条目

有用的功能,fastcache 提供两个api SaveToFileLoadFromFile ,可以在程序正常退出时保存缓存的数据,当再次启动时从文件载入数据。

fastcache 使用例子

package main

import (
"bytes"
"fmt"
"github.com/VictoriaMetrics/fastcache"
"io/ioutil"
"os"
)

func main() {

filePath := "tmp.db"

imgBuf, err := ioutil.ReadFile("IMG_20190630_150511.jpg")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("imgBuf len", len(imgBuf))

c := fastcache.New(128 * 1024 * 1024)
defer func() {
c.SaveToFile(filePath)
c.Reset()
}()

if _, err := os.Stat(filePath); err == nil {
c, err = fastcache.LoadFromFile(filePath)
}

fmt.Println("aaa:", string(c.Get(nil, []byte("aaa"))))

c.Set([]byte("key"), []byte("value"))
fmt.Println("key:", string(c.Get(nil, []byte("key"))))

c.Set([]byte("aaa"), []byte("bbb"))
fmt.Println("aaa:", string(c.Get(nil, []byte("aaa"))))

c.Del([]byte("key"))

var buf []byte
if !c.Has([]byte("img")) {
fmt.Println("!has img key, SetBig")
c.SetBig([]byte("img"), imgBuf)
}

buf = c.GetBig(buf[:0], []byte("img"))
if !bytes.Equal(buf, imgBuf) {
fmt.Println("not Equal")
return
}
fmt.Println("Equal", len(imgBuf), len(buf))
}

参考

0

See Also

Nearby


Discussion

Login Topics