go是一个非常高效的语言, 对并发的处理非常的好, 对于内存方面沿用类似java的GC方式进行内存的回收. 但是GO的GC的回收非常的耗时.所以提出了高效缓存的机制. 现在高效缓存包括:Bigcache Freecache, groupCahce.下面对三种方式的实现机制做一个解析:
Bigcache:
下面这段是原文的介绍:
Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance.BigCache keeps entries on heap but omits GC for them.To achieve that operations on bytes arrays take place,therefore entries (de)serialization in front of the cache will be needed in most use cases.
意思是Bigcache是一个快速,同步,内存外的缓存, 其保证大条目数据而不影响性能, Bigcahche保证所有数据都在堆上而忽略系统的GC. 使用bytes arrays完成操作. 因此在使用前需要进行序列化和反序列话.
Bigcache使用map[uint64]uint32作为hash的key值以及vaule的全局偏移量.
FreeCache
官方的介绍如下:
FreeCache avoids GC overhead by reducing the number of pointers. No matter how many entries stored in it, there are only 512 pointers. The data set is sharded into 256 segments by the hash value of the key. Each segment has only two pointers, one is the ring buffer that stores keys and values, the other one is the index slice which used to lookup for an entry. Each segment has its own lock, so it supports high concurrent access.
Freechche 通过减少指针的数量从而避免过多的GC. 不管系统保存多少指针, 这里只有512个指针. 数据利用key-value的形式被分配到256个段中. 每个段中包含两个指针,一个是循环链用于存储key-values,另外一个是片的索引用于全局的搜索. 每个段都有其独立的锁, 因此它支持高并发访问.
FreeCache是一个近似LRU的算法, 什么是LRU算法? LRU是内存管理的一种方式,即内存页置换方式, 对于已经分配的但是没有使用的数据进行缓存, 当缓存满了之后,按照一定的规则顺序对存储的数据进行置换.
GroupCache
目前Groupcache仅支持go语言,常常作为memcache的替换方案. Groupcache不需要额外的设置,
Groupcache即是客户端的lib也是服务端的lib.
GroupCache不支持更改和删除的功能,当value的值设定之后不能更改, 即没有过期的时间,也没有删除的功能.
从这三种方式github上面go语言的start的数量来看,Groupcache是最高的.
最近在研究开源的mattermost代码,其 后端也是使用的Groupchce实现的.
目前对这三种缓存还没有实际的使用经验,后续如果继续做研究,再写新的总结.
博客链接: