10

Otter:基于 S3-FIFO 算法的最快 Go 内存缓存

 8 months ago
source link: https://www.jdon.com/71245.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Otter:基于 S3-FIFO 算法的最快 Go 内存缓存

没有一个 Golang 缓存库是真正无争用的。所有缓存库都带有互斥锁和一些删除策略的标准映射Map。这样,这些Go缓存库就无法达到其他语言(例如Caffeine)的缓存速度。

例如,来自 Dgraph 实验室的最快缓存名为Ristretto,它最多比竞争对手快 30%(Otter 快很多倍),并且命中率令人恶心(1.05%的比率)。

因此,我希望获得最快、最易于使用的缓存,具有出色的命中率和作者的支持,Otter 旨在纠正这种不幸的误解。

Otter 基于以下论文:

该库有很多功能,例如:

  • 简单的API:只需在构建器中设置您想要的参数即可享受
  • 自动配置:Otter 根据应用程序的并行性自动配置
  • 泛型:您可以安全地使用任何可比较的类型作为键,使用任何类型作为值
  • TTL:过期的值将自动从缓存中删除
  • 基于成本的驱逐:Otter支持根据每件物品的成本进行驱逐
  • 卓越的性能:Otter是目前最快的缓存库,在竞争对手中遥遥领先
  • 命中率高:采用新的S3-FIFO算法,效果极佳

Otter使用构建器模式,可以让你方便地创建具有不同参数的缓存对象

package main

import (
    "github.com/maypok86/otter"
)

func main() {
   // NewBuilder 创建一个创建器,并将未来缓存容量设置为 1000 个元素。
    builder, err := otter.NewBuilder[string, string](1000)
    if err != nil {
        panic(err)
    }

// StatsEnabled 决定缓存运行时是否要计算统计数据。
    builder.StatsEnabled(true)

// 成本设置函数,用于动态计算键值对的权重。
    builder.Cost(func(key string, value string) uint32 {
        return uint32(len(value))
    })

// 生成一个新的缓存对象,或者
    // 如果向生成器传递了无效参数,则返回错误。
    cache, err := builder.Build()
    if err != nil {
        panic(err)
    }

cache.Close()
}
package main

import (
    "fmt"
    "time"

"github.com/maypok86/otter"
)

func main() {
   // 创建一个容量等于 10000 个元素的缓存
    cache, err := otter.MustBuilder[string, string](10_000).Build()
    if err != nil {
        panic(err)
    }

// 用 ttl(1 小时)设置键值对  ;
    cache.SetWithTTL("key", "value", time.Hour)

// 从缓存中获取值
    value, ok := cache.Get("key")
    if !ok {
        panic("not found key")
    }
    fmt.Println(value)

// 从缓存中删除键值对
    cache.Delete("key")

// 删除数据并停止运行程序
    cache.Close()
}

 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK