【Golang开源项目】Golang高性能内存缓存库BigCache设计与分析

项目地址

BigCache 是一个快速,支持并发访问,自淘汰的内存型缓存,可以在存储大量元素时依然保持高性能。BigCache将元素保存在堆上却避免了GC的开销。

背景介绍

BigCache的作者在项目里遇到了如下的需求:

  • 支持http协议
  • 支持 10 k 10k 10kRPS ,其中读写各占一半
  • cache缓存至少 10 10 10分钟
  • 平均 r t = 5 m s , p 99 < = 10 m s , p 999 < = 400 m s rt=5ms,p99<=10ms,p999<=400ms rt=5ms,p99<=10ms,p999<=400ms
    开发的缓存库需要保证:
  • 即使有百万的缓存对象速度也要很快
  • 支持高并发访问
  • 支持过期自动删除

简单入门

func Test_BigCache(t *testing.T) {
	cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) //定义cache
	cache.Set("my-unique-key", []byte("value")) //设置k,v键值对
	entry, _ := cache.Get("my-unique-key") //获取k,v键值对
	t.Log(string(entry))
}

配置文件

config字段说明

字段名类型含义
Shardsint缓存分片数,值必须是 2 的幂
LifeWindowtime.Duration条目可以被逐出的时间,近似可以理解为缓存时间
CleanWindowtime.Duration删除过期条目(清理)之间的间隔。如果设置为 <= 0,则不执行任何操作。设置为 < 1 秒会适得其反,因为 bigcache 的分辨率为 1 秒。
MaxEntriesInWindowint生命周期窗口中的最大条目数。仅用于计算缓存分片的初始大小。如果设置了适当的值,则不会发生额外的内存分配。
MaxEntrySizeint条目的最大大小(以字节为单位)。仅用于计算缓存分片的初始大小。
StatsEnabledboolStatsEnabled如果为true,则计算请求缓存资源的次数。
Verbosebool是否以详细模式打印有关新内存分配的信息
HasherHasher哈希程序用于在字符串键和无符号 64 位整数之间进行映射,默认情况下使用 fnv64 哈希
HardMaxCacheSizeint是BytesQueue 大小的限制 MB。它可以防止应用程序占用计算机上的所有可用内存,从而防止运行 OOM Killer。
OnRemovefunc(key string, entry []byte)OnRemove 是当最旧的条目由于过期时间或没有为新条目留出空间或调用 delete 而被删除时触发的回调。如果指定了 OnRemoveWithMetadata,则忽略。
OnRemoveWithMetadatafunc(key string, entry []byte, keyMetadata Metadata)OnRemoveWithMetadata 是当最旧的条目由于过期时间或没有为新条目留出空间或调用 delete 而被删除时触发的回调,携带有关该特定条目的详细信息的结构。
OnRemoveWithReasonfunc(key string, entry []byte, reason RemoveReason)OnRemoveWithReason 是当最旧的条目由于过期时间或没有为新条目留出空间或调用了 delete 而被删除时触发的回调,将传递一个表示原因的常量。如果指定了 OnRemove,则忽略。
onRemoveFilterint和OnRemoveWithReason一起使用,阻止 bigcache 解包它们,从而节省 CPU
LoggerLogger日志记录接口

说明:

  • LifeWindow 是一个时间。在此之后,条目可以称为死条目,但不能删除。
  • CleanWindow 是一个时间。在此之后,将删除所有无效条目,但不会删除仍具有生命的条目。
  • HardMaxCacheSize 默认值为 0,表示大小不受限制。当限制高于 0 并达到时,新条目将覆盖最旧的条目。由于 Shards 的额外内存,最大内存消耗将大于 HardMaxCacheSize。每个分片都会消耗额外的内存来映射键和统计信息 (map[uint64]uint32),此映射的大小等于缓存中的条目数 ~ 2×(64+32)×n 位 + 开销或映射本身。
  • OnRemove,OnRemoveWithMetadata ,OnRemoveWithReason 这三个跟删除有关的属性默认值为 nil,表示没有回调,并且会阻止解开最早的条目。

配置代码文件


// Config for BigCache
type Config struct {
	// Number of cache shards, value must be a power of two
	Shards int
	// Time after which entry can be evicted
	LifeWindow time.Duration
	// Interval between removing expired entries (clean up).
	// If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution.
	CleanWindow time.Duration
	// Max number of entries in life window. Used only to calculate initial size for cache shards.
	// When proper value is set then additional memory allocation does not occur.
	MaxEntriesInWindow int
	// Max size of entry in bytes. Used only to calculate initial size for cache shards.
	MaxEntrySize int
	// StatsEnabled if true calculate the number of times a cached resource was requested.
	StatsEnabled bool
	// Verbose mode prints information about new memory allocation
	Verbose bool
	// Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used.
	Hasher Hasher
	// HardMaxCacheSize is a limit for BytesQueue size in MB.
	// It can protect application from consuming all available memory on machine, therefore from running OOM Killer.
	// Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then
	// the oldest entries are overridden for the new ones. The max memory consumption will be bigger than
	// HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys
	// and statistics (map[uint64]uint32) the size of this map is equal to number of entries in
	// cache ~ 2×(64+32)×n bits + overhead or map itself.
	HardMaxCacheSize int
	// OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	// ignored if OnRemoveWithMetadata is specified.
	OnRemove func(key string, entry []byte)
	// OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called. A structure representing details about that specific entry.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata)
	// OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left
	// for the new entry, or because delete was called. A constant representing the reason will be passed through.
	// Default value is nil which means no callback and it prevents from unwrapping the oldest entry.
	// Ignored if OnRemove is specified.
	OnRemoveWithReason func(key string, entry []byte, reason RemoveReason)

	onRemoveFilter int

	// Logger is a logging interface and used in combination with `Verbose`
	// Defaults to `DefaultLogger()`
	Logger Logger
}

默认配置

DefaultConfig 使用默认值初始化配置。当可以提前预测 BigCache 的负载时,最好使用自定义配置

字段名含义
Shards1024缓存分片数是1024
LifeWindoweviction自定义过期时间
CleanWindow1 * time.Second每隔1秒就清理失效数据
MaxEntriesInWindow1000 * 10 * 60生命周期窗口中的最大条目数为6e5
MaxEntrySize500条目的最大大小为500字节
StatsEnabledfalse不计算请求缓存资源的次数
Verbosetrue以详细模式打印有关新内存分配的信息
Hasherfnv64哈希程序,fnv64 哈希
HardMaxCacheSize0BytesQueue 大小无限制
LoggerDefaultLogger日志记录接口

优点:支持自定义过期时间,清理失效数据的间隔为最小间隔、效率高
缺点:BytesQueue 大小无限制,容易造成内存占用过高
默认配置代码:

func DefaultConfig(eviction time.Duration) Config {
	return Config{
		Shards:             1024,
		LifeWindow:         eviction,
		CleanWindow:        1 * time.Second,
		MaxEntriesInWindow: 1000 * 10 * 60,
		MaxEntrySize:       500,
		StatsEnabled:       false,
		Verbose:            true,
		Hasher:             newDefaultHasher(),
		HardMaxCacheSize:   0,
		Logger:             DefaultLogger(),
	}
}

数据结构

前提说明:BigCache 是快速、并发、逐出缓存,旨在保留大量条目而不影响性能。它将条目保留在堆上,但省略了它们的 GC。为了实现这一点,操作发生在字节数组上,因此在大多数用例中,都需要在缓存前面进行条目**(反序列化)**。

BigCache数据结构

字段名类型含义
shards[]*cacheShard缓存分片数据
lifeWindowuint64缓存时间,对应配置里的LifeWindow
clockclock时间计算函数
hashHasher哈希函数
configConfig配置文件
shardMaskuint64值为(config.Shards-1),寻找分片位置时使用的参数,可以理解为对config.Shards取余后的最大值
closechan struct{}关闭通道
type BigCache struct {
	shards     []*cacheShard
	lifeWindow uint64
	clock      clock
	hash       Hasher
	config     Config
	shardMask  uint64
	close      chan struct{}
}

cacheShard数据结构

字段名类型含义
hashmapmap[uint64]uint32索引列表,key为存储的key,value为该key在entries里的位置
entriesqueue.BytesQueue实际数据存储的地方
locksync.RWMutex互斥锁,用于并发读写
entryBuffer[]byte入口缓冲区
onRemoveonRemoveCallback删除回调函数
isVerbosebool是否详细模式打印有关新内存分配的信息
statsEnabledbool是否计算请求缓存资源的次数
loggerLogger日志记录函数
clockclock时间计算函数
lifeWindowuint64缓存时间,对应配置里的LifeWindow
hashmapStatsmap[uint64]uint32存储缓存请求次数
statsStats存储缓存统计信息
cleanEnabledbool是否可清理,由config.CleanWindow决定
type cacheShard struct {
	hashmap     map[uint64]uint32
	entries     queue.BytesQueue
	lock        sync.RWMutex
	entryBuffer []byte
	onRemove    onRemoveCallback

	isVerbose    bool
	statsEnabled bool
	logger       Logger
	clock        clock
	lifeWindow   uint64

	hashmapStats map[uint64]uint32
	stats        Stats
	cleanEnabled bool
}

BytesQueue数据结构

BytesQueue 是一种基于 bytes 数组的 fifo 非线程安全队列类型。对于每个推送操作,都会返回条目的索引。它可用于稍后读取条目。

字段名类型含义
fullbool队列是否已满
array[]byte实际数据存储的地方
capacityint容量
maxCapacityint最大容量
headint队首位置
tailint下次可以插入的元素位置
countint当前存在的元素数量
rightMarginint右边界
headerBuffer[]byte插入时的临时缓冲区
verbosebool是否详细模式打印有关新内存分配的信息
type BytesQueue struct {
	full         bool
	array        []byte
	capacity     int
	maxCapacity  int
	head         int
	tail         int
	count        int
	rightMargin  int
	headerBuffer []byte
	verbose      bool
}

优秀设计

处理并发访问

设计点1:将数据打散后存储

通用解法: 缓存支持并发访问是很基本的要求,比较常见的解决访问是对缓存整体加读写锁,在同一时间只允许一个协程修改缓存内容。这样的缺点是锁可能会阻塞后续的操作,而且高频的加锁、解锁操作会导致缓存性能降低。

设计点: B i g C a c h e BigCache BigCache使用一个 s h a r d shard shard数组来存储数据,将数据打散到不同的 s h a r d shard shard里,每个 s h a r d shard shard里都有一个小的 l o c k lock lock,从而减小了锁的粒度,提高访问性能。

设计点2:打散数据过程中借助位运算加快计算速度

接下来看一下将某个数据放到缓存的过程的源代码:

// Set saves entry under the key
func (c *BigCache) Set(key string, entry []byte) error {
	hashedKey := c.hash.Sum64(key)
	shard := c.getShard(hashedKey)
	return shard.set(key, hashedKey, entry)
}
func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) {
	return c.shards[hashedKey&c.shardMask]
}

可以得到 s e t set set的过程如下:

  • 进行 h a s h hash hash操作,将 s t r i n g string string类型 k e y key key哈希为一个 u i n t 64 uint64 uint64类型的 h a s h e d K e y hashedKey hashedKey
  • 根据 h a s h e d K e y hashedKey hashedKey s h a r d i n g sharding sharding,最后落到的 s h a r d shard shard的下标为 h a s h e d K e y % n hashedKey\%n hashedKey%n,其中 n n n是分片数量。理想情况下,每次请求会均匀地落在各自的分片上,单个 s h a r d shard shard的压力就会很小。
  • 调用对应 s h a r d shard shard的set方法来设置缓存

设计点:
n n n 2 2 2的幂次方的时候,对于任意的 x x x,下面的公式都成立的。
x   m o d   N = ( x & ( N − 1 ) ) x\ mod\ N = (x \& (N − 1)) x mod N=(x&(N1))
所以可以借助位运算快速计算余数,因此倒推回去 缓存分片数必须要设置为 2 2 2的幂次方

设计点3 避免栈上的内存分配

默认的哈希算法为 f n v 64 fnv64 fnv64算法,该算法采用位运算的方式在栈上运算,避免了在堆上分配内存

package bigcache

// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations.
// Its Sum64 method will lay the value out in big-endian byte order.
// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function
func newDefaultHasher() Hasher {
	return fnv64a{}
}

type fnv64a struct{}

const (
	// offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash
	offset64 = 14695981039346656037
	// prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash
	prime64 = 1099511628211
)

// Sum64 gets the string and returns its uint64 hash value.
func (f fnv64a) Sum64(key string) uint64 {
	var hash uint64 = offset64
	for i := 0; i < len(key); i++ {
		hash ^= uint64(key[i])
		hash *= prime64
	}

	return hash
}

减少GC开销

设计点1:利用go1.5+特性,减少GC扫描

g o l a n g golang golang里实现缓存最简单的方式是 m a p map map来存储元素,比如 m a p [ s t r i n g ] I t e m map[string]Item map[string]Item
使用 m a p map map的缺点为垃圾回收器 G C GC GC会在标记阶段访问 m a p map map里的每一个元素,当 m a p map map里存储了大量数据的时候会降低程序性能。

B i g C a c h e BigCache BigCache使用了 g o 1.5 go1.5 go1.5版本以后的特性:如果使用的map的key和value中都不包含指针,那么GC会忽略这个map
具体而言, B i g C a c h e BigCache BigCache使用 m a p [ u i n t 64 ] u i n t 32 map[uint64]uint32 map[uint64]uint32
来存储数据,不包含指针, G C GC GC就会自动忽略这个 m a p map map

m a p map map k e y key key存储的是缓存的 k e y key key经过 h a s h hash hash函数后得到的值
m a p map map v a l u e value value存储的是序列化后的数据在全局 [ ] b y t e []byte []byte中的下标。
因为 B i g C a c h e BigCache BigCache是将存入缓存的 v a l u e value value序列化为 b y t e byte byte数组,然后将该数组追加到全局的 b y t e byte byte数组里(说明:结合前面的打散思想可以得知一个 s h a r d shard shard对应一个全局的 b y t e byte byte数组
这样做的缺点是删除元素的开销会很大,因此 B i g C a c h e BigCache BigCache里也没有提供删除指定 k e y key key的接口,删除元素靠的是全局的过期时间或是缓存的容量上限,是先进先出的队列类型的过期。

性能测试

项目开发者给出了项目和主流缓存方案的 B e n c h m a r k s Benchmarks Benchmarks结果和 G C GC GC测试结果
测试文件链接

在这里插入图片描述
在这里插入图片描述

参考
妙到颠毫: bigcache优化技巧
[译] Go开源项目BigCache如何加速并发访问以及避免高额的GC开销

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/319446.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

四、Qt 的第一个demo

在上一篇章节里《三、Qt Creator 使用》&#xff0c;我们介绍了如何使用Qt Creator创建一个简单的带窗体的demo&#xff0c;在这一章节里&#xff0c;我们详细讲解一下这个demo的文件组成&#xff0c;及主函数&#xff0c;并在UI上加一些控件&#xff0c;实现一些简单的功能。 …

C# Winform翻牌子记忆小游戏

效果 源码 新建一个winform项目命名为Matching Game&#xff0c;选用.net core 6框架 并把Form1.cs代码修改为 using Timer System.Windows.Forms.Timer;namespace Matching_Game {public partial class Form1 : Form{private const int row 4;private const int col 4;p…

yolov5口罩检测模型

1 项目背景及意义 全球范围内的公共卫生安全和人脸识别技术的发展。在面对新型冠状病毒等传染病的爆发和传播风险时&#xff0c;佩戴口罩成为一种重要的防护措施。然而&#xff0c;现有的人脸识别系统在识别戴口罩的人脸时存在一定的困难。 通过口罩识别技术&#xff0c;可以…

分布式系统中的CAP原理

分布式系统中的CAP原理 本文已收录至我的个人网站&#xff1a;程序员波特&#xff0c;主要记录Java相关技术系列教程&#xff0c;共享电子书、Java学习路线、视频教程、简历模板和面试题等学习资源&#xff0c;让想要学习的你&#xff0c;不再迷茫。 简介 在分布式系统中&…

LeetCode刷题(ACM模式)-05栈与队列

参考引用&#xff1a;代码随想录 注&#xff1a;每道 LeetCode 题目都使用 ACM 代码模式&#xff0c;可直接在本地运行&#xff0c;蓝色字体为题目超链接 0. 栈与队列理论基础 21天学通C读书笔记&#xff08;二十三&#xff1a;自适应容器&#xff1a;栈和队列&#xff09; 堆…

利用GraalVM将java文件变成exe可执行文件

上期文章已经配置好了环境&#xff1a;Springboot3新特性&#xff1a;开发第一个 GraalVM 本机应用程序(完整教程)-CSDN博客 在桌面上创建一个HelloWorld.java的文件。 public class HelloWorld{public static void main (String[] args){System.out.println("Hello,Wor…

Clickhouse表引擎之CollapsingMergeTree引擎的原理与使用

前言 继续上次关于clickhouse的一些踩坑点&#xff0c;今天讲讲另外一个表引擎——CollapsingMergeTree。这个对于引擎对于数据量较大的场景是个不错的选择。注意&#xff0c;选择clickhouse的一般原因都是为了高效率查询&#xff0c;提高用户体验感&#xff0c;说白了就是以空…

blender 导入到 Marvelous Designer

1&#xff09; 将模型的所有部分合并为一个单独的mesh 2&#xff09; 先调整计量单位&#xff1a; 3&#xff09;等比缩放&#xff0c;身高调整到180cm左右 4&#xff09;应用当前scale 首先&#xff0c;选中你要修改的物体&#xff0c;然后按下Ctrl-A键&#xff0c;打开应用…

蓝桥杯练习题(九)

&#x1f4d1;前言 本文主要是【算法】——蓝桥杯练习题&#xff08;九&#xff09;的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是听风与他&#x1f947; ☁️博客首页&#xff1a;CSDN主页听风与他 …

数据结构学习笔记——查找算法中的树形查找(红黑树)

目录 一、红黑树的定义&#xff08;一&#xff09;黑/红结点、叶子节点&#xff08;二&#xff09;黑色完美平衡 二、红黑树的性质&#xff08;一&#xff09;黑高和高度&#xff08;二&#xff09;叶子结点个数 三、红黑树与AVL对比 一、红黑树的定义 红黑树是一棵二叉排序树…

【OpenGauss源码学习 —— 执行器(execMain)】

执行器&#xff08;execMain&#xff09; 概述文件内容作用执行的操作主要函数概述 部分函数详细分析ExecutorStart 函数standard_ExecutorStart 函数 ExecutorRun 函数standard_ExecutorRun 函数 ExecutorFinish 函数standard_ExecutorFinish 函数 ExecutorEnd 函数standard_E…

数据库单表查询

1、显示所有职工的基本信息。 2、查询所有职工所属部门的部门号&#xff0c;不显示重复的部门号。 3、求出所有职工的人数。 4、列出最高工和最低工资。 5、列出职工的平均工资和总工资。 6、创建一个只有职工号、姓名和参加工作的新表&#xff0c;名为工作日期表…

基于PyQT的图片批处理系统

项目背景&#xff1a; 随着数字摄影技术的普及&#xff0c;人们拍摄和处理大量图片的需求也越来越高。为了提高效率&#xff0c;开发一个基于 PyQt 的图片批处理系统是很有意义的。该系统可以提供一系列图像增强、滤波、水印、翻转、放大缩小、旋转等功能&#xff0c;使用户能够…

单容水箱液位定值控制实验

实验1 单容水箱液位定值控制实验 一、实验目的 1、通过实验熟悉单回路反馈控制系统的组成和工作原理。 2、分析分别用P、PI和PID调节时的过程图形曲线。 3、定性地研究P、PI和PID调节器的参数对系统性能的影响。 二、实验设备 A3000现场系统&#xff0c;任何一个控制系统…

Java项目:03 基于Springboot的销售培训考评管理系统

项目介绍 企业的销售要进行培训&#xff0c;由技术人员进行辅导并考评检测培训效果&#xff0c;所以有了这个小系统。实现了系统的登录验证、请求拦截验证、基础模块&#xff08;用户管理、角色管理、销售管理&#xff09;、业务模块&#xff08;评分管理、评分结果&#xff0…

springboot 企业微信 网页授权

html 引入jquery $(function () {// alert("JQ onready");// 当前企业的 corp_idconst corp_id xxxxxx;// 重定向 URL → 最终打开的画面地址&#xff0c;域名是在企业微信上配置好的域名const redirect_uri encodeURI(http://xxxxx.cn);//企业的agentId 每个应用都…

基于SpringBoot的房屋交易平台的设计与实现

&#x1f345;点赞收藏关注 → 私信领取本源代码、数据库&#x1f345; 本人在Java毕业设计领域有多年的经验&#xff0c;陆续会更新更多优质的Java实战项目希望你能有所收获&#xff0c;少走一些弯路。&#x1f345;关注我不迷路&#x1f345;一 、设计说明 1.1 研究背景 互…

Nightingale 夜莺监控系统 - 部署篇(1)

Author&#xff1a;rab 官方文档&#xff1a;https://flashcat.cloud/docs 目录 一、概述二、架构2.1 中心机房架构2.2 边缘下沉式混杂架构 三、环境四、部署4.1 中心机房架构部署4.1.1 MySQL4.1.2 Redis4.1.3 Prometheus4.1.4 n9e4.1.5 Categraf4.1.6 验证4.1.7 配置数据源 4…

安装、运行和控制AI apps在您的计算机上一键式

pinokio 你是否曾为安装、运行和自动化 AI 应用程序和大模型而感到困惑&#xff1f;是否希望有一个简单而强大的工具来满足你的需求&#xff1f;如果是这样&#xff0c;那么 Pinokio 将会是你的理想选择&#xff01;Pinokio 是一款革命性的人工智能浏览器&#xff0c;是一个开…
最新文章