脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - golang实现本地缓存Localcache的方法

golang实现本地缓存Localcache的方法

2022-01-04 22:42Golang梦工厂AsongGo Golang

使用二维数组存储数据的相比于bigcache的优势在于可以直接根据索引删除对应的数据,虽然也会有虫洞的问题,但是我们可以记录下来虫洞的索引,不断填充。

golang实现本地缓存Localcache的方法

前言

哈喽,大家好,我是asong,经过了前面两篇的介绍,我们已经基本了解该如何设计一个本地缓存了,本文就是这个系列的终结篇,自己动手实现一个本地缓存,接下来且听我细细道来!!!

本文代码已经上传到github:https://github.com/asong2020/go-localcache

现在这一版本算是一个1.0,后续会继续进行优化和迭代。

第一步:抽象接口

第一步很重要,以面向接口编程为原则,我们先抽象出来要暴露给用户的方法,给用户提供简单易懂的方法,因此我抽象出来的结果如下:

  1. // ICache abstract interface
  2. type ICache interface {
  3. // Set value use default expire time. default does not expire.
  4. Set(key string, value []byte) error
  5. // Get value if find it. if value already expire will delete.
  6. Get(key string) ([]byte, error)
  7. // SetWithTime set value with expire time
  8. SetWithTime(key string, value []byte, expired time.Duration) error
  9. // Delete manual removes the key
  10. Delete(key string) error
  11. // Len computes number of entries in cache
  12. Len() int
  13. // Capacity returns amount of bytes store in the cache.
  14. Capacity() int
  15. // Close is used to signal a shutdown of the cache when you are done with it.
  16. // This allows the cleaning goroutines to exit and ensures references are not
  17. // kept to the cache preventing GC of the entire cache.
  18. Close() error
  19. // Stats returns cache's statistics
  20. Stats() Stats
  21. // GetKeyHit returns key hit
  22. GetKeyHit(key string) int64
  23. }
  • Set(key string, value []byte):使用该方法存储的数据使用默认的过期时间,如果清除过期的异步任务没有enable,那么就永不过期,否则默认过期时间为10min。
  • Get(key string) ([]byte, error):根据key获取对象内容,如果数据过期了会在这一步删除。
  • SetWithTime(key string, value []byte, expired time.Duration):存储对象是使用自定义过期时间
  • Delete(key string) error:根据key删除对应的缓存数据
  • Len() int:获取缓存的对象数量
  • Capacity() int:获取当前缓存的容量
  • Close() error:关闭缓存
  • Stats() Stats:缓存监控数据
  • GetKeyHit(key string) int64:获取key的命中率数据

第二步:定义缓存对象

第一步我们抽象好了接口,下面就要定义一个缓存对象实例实现接口,先看定义结构:

  1. type cache struct {
  2. // hashFunc represents used hash func
  3. hashFunc HashFunc
  4. // bucketCount represents the number of segments within a cache instance. value must be a power of two.
  5. bucketCount uint64
  6. // bucketMask is bitwise AND applied to the hashVal to find the segment id.
  7. bucketMask uint64
  8. // segment is shard
  9. segments []*segment
  10. // segment lock
  11. locks []sync.RWMutex
  12. // close cache
  13. close chan struct{}
  14. }
  • hashFunc:分片要用的哈希函数,用户可以自行定义,实现HashFunc接口即可,默认使用fnv算法。
  • bucketCount:分片的数量,一定要是偶数,默认分片数为256。
  • bucketMask:因为分片数是偶数,所以可以分片时可以使用位运算代替取余提升性能效率,hashValue % bucketCount == hashValue & bucketCount - 1。
  • segments:分片对象,每个分片的对象结构我们在后面介绍。
  • locks:每个分片的读写锁
  • close:关闭缓存对象时通知其他goroutine暂停

接下来我们来写cache对象的构造函数:

  1. // NewCache constructor cache instance
  2. func NewCache(opts ...Opt) (ICache, error) {
  3. options := &options{
  4. hashFunc: NewDefaultHashFunc(),
  5. bucketCount: defaultBucketCount,
  6. maxBytes: defaultMaxBytes,
  7. cleanTime: defaultCleanTIme,
  8. statsEnabled: defaultStatsEnabled,
  9. cleanupEnabled: defaultCleanupEnabled,
  10. }
  11. for _, each := range opts{
  12. each(options)
  13. }
  14.  
  15. if !isPowerOfTwo(options.bucketCount){
  16. return nil, errShardCount
  17. }
  18.  
  19. if options.maxBytes <= 0 {
  20. return nil, ErrBytes
  21. }
  22.  
  23. segments := make([]*segment, options.bucketCount)
  24. locks := make([]sync.RWMutex, options.bucketCount)
  25.  
  26. maxSegmentBytes := (options.maxBytes + options.bucketCount - 1) / options.bucketCount
  27. for index := range segments{
  28. segments[index] = newSegment(maxSegmentBytes, options.statsEnabled)
  29. }
  30.  
  31. c := &cache{
  32. hashFunc: options.hashFunc,
  33. bucketCount: options.bucketCount,
  34. bucketMask: options.bucketCount - 1,
  35. segments: segments,
  36. locks: locks,
  37. close: make(chan struct{}),
  38. }
  39. if options.cleanupEnabled {
  40. go c.cleanup(options.cleanTime)
  41. }
  42.  
  43. return c, nil
  44. }

这里为了更好的扩展,我们使用Options编程模式,我们的构造函数主要做三件事:

  • 前置参数检查,对于外部传入的参数,我们还是要做基本的校验
  • 分片对象初始化
  • 构造缓存对象

这里构造缓存对象时我们要先计算每个分片的容量,默认整个本地缓存256M的数据,然后在平均分到每一片区内,用户可以自行选择要缓存的数据大小。

第三步:定义分片结构

每个分片结构如下:

  1. type segment struct {
  2. hashmap map[uint64]uint32
  3. entries buffer.IBuffer
  4. clock clock
  5. evictList *list.List
  6. stats IStats
  7. }
  • hashmp:存储key所对应的存储索引
  • entries:存储key/value的底层结构,我们在第四步的时候介绍,也是代码的核心部分。
  • clock:定义时间方法
  • evicList:这里我们使用一个队列来记录old索引,当容量不足时进行删除(临时解决方案,当前存储结构不适合使用LRU淘汰算法)
  • stats:缓存的监控数据。

接下来我们再来看一下每个分片的构造函数:

  1. func newSegment(bytes uint64, statsEnabled bool) *segment {
  2. if bytes == 0 {
  3. panic(fmt.Errorf("bytes cannot be zero"))
  4. }
  5. if bytes >= maxSegmentSize{
  6. panic(fmt.Errorf("too big bytes=%d; should be smaller than %d", bytes, maxSegmentSize))
  7. }
  8. capacity := (bytes + segmentSize - 1) / segmentSize
  9. entries := buffer.NewBuffer(int(capacity))
  10. entries.Reset()
  11. return &segment{
  12. entries: entries,
  13. hashmap: make(map[uint64]uint32),
  14. clock: &systemClock{},
  15. evictList: list.New(),
  16. stats: newStats(statsEnabled),
  17. }
  18. }

这里主要注意一点:

我们要根据每个片区的缓存数据大小来计算出容量,与上文的缓存对象初始化步骤对应上了。

第四步:定义缓存结构

缓存对象现在也构造好了,接下来就是本地缓存的核心:定义缓存结构。

bigcache、fastcache、freecache都使用字节数组代替map存储缓存数据,从而减少GC压力,所以我们也可以借鉴其思想继续保持使用字节数组,这里我们使用二维字节切片存储缓存数据key/value;画个图表示一下:

golang实现本地缓存Localcache的方法

使用二维数组存储数据的相比于bigcache的优势在于可以直接根据索引删除对应的数据,虽然也会有虫洞的问题,但是我们可以记录下来虫洞的索引,不断填充。

每个缓存的封装结构如下:

golang实现本地缓存Localcache的方法

基本思想已经明确,接下来看一下我们对存储层的封装:

  1. type Buffer struct {
  2. array [][]byte
  3. capacity int
  4. index int
  5. // maxCount = capacity - 1
  6. count int
  7. // availableSpace If any objects are removed after the buffer is full, the idle index is logged.
  8. // Avoid array "wormhole"
  9. availableSpace map[int]struct{}
  10. // placeholder record the index that buffer has stored.
  11. placeholder map[int]struct{}
  12. }
  • array [][]byte:存储缓存对象的二维切片
  • capacity:缓存结构的最大容量
  • index:索引,记录缓存所在的位置的索引
  • count:记录缓存数量
  • availableSpace:记录"虫洞",当缓存对象被删除时记录下空闲位置的索引,方便后面容量满了后使用"虫洞"
  • placeholder:记录缓存对象的索引,迭代清除过期缓存可以用上。

向buffer写入数据的流程(不贴代码了):

golang实现本地缓存Localcache的方法

第五步:完善向缓存写入数据方法

上面我们定义好了所有需要的结构,接下来就是填充我们的写入缓存方法就可以了:

  1. func (c *cache) Set(key string, value []byte) error {
  2. hashKey := c.hashFunc.Sum64(key)
  3. bucketIndex := hashKey&c.bucketMask
  4. c.locks[bucketIndex].Lock()
  5. defer c.locks[bucketIndex].Unlock()
  6. err := c.segments[bucketIndex].set(key, hashKey, value, defaultExpireTime)
  7. return err
  8. }
  9.  
  10. func (s *segment) set(key string, hashKey uint64, value []byte, expireTime time.Duration) error {
  11. if expireTime <= 0{
  12. return ErrExpireTimeInvalid
  13. }
  14. expireAt := uint64(s.clock.Epoch(expireTime))
  15.  
  16. if previousIndex, ok := s.hashmap[hashKey]; ok {
  17. if err := s.entries.Remove(int(previousIndex)); err != nil{
  18. return err
  19. }
  20. delete(s.hashmap, hashKey)
  21. }
  22.  
  23. entry := wrapEntry(expireAt, key, hashKey, value)
  24. for {
  25. index, err := s.entries.Push(entry)
  26. if err == nil {
  27. s.hashmap[hashKey] = uint32(index)
  28. s.evictList.PushFront(index)
  29. return nil
  30. }
  31. ele := s.evictList.Back()
  32. if err := s.entries.Remove(ele.Value.(int)); err != nil{
  33. return err
  34. }
  35. s.evictList.Remove(ele)
  36. }
  37. }

流程分析如下:

根据key计算哈希值,然后根据分片数获取对应分片位置

如果当前缓存中存在相同的key,则先删除,在重新插入,会刷新过期时间

封装存储结构,根据过期时间戳、key长度、哈希大小、缓存对象进行封装

将数据存入缓存,如果缓存失败,移除最老的数据后再次重试

第六步:完善从缓存读取数据方法

第一步根据key计算哈希值,再根据分片数获取对应的分片位置:

  1. func (c *cache) Get(key string) ([]byte, error) {
  2. hashKey := c.hashFunc.Sum64(key)
  3. bucketIndex := hashKey&c.bucketMask
  4. c.locks[bucketIndex].RLock()
  5. defer c.locks[hashKey&c.bucketMask].RUnlock()
  6. entry, err := c.segments[bucketIndex].get(key, hashKey)
  7. if err != nil{
  8. return nil, err
  9. }
  10. return entry,nil
  11. }

第二步执行分片方法获取缓存数据:

  • 先根据哈希值判断key是否存在于缓存中,不存返回key没有找到
  • 从缓存中读取数据得到缓存中的key判断是否发生哈希冲突
  • 判断缓存对象是否过期,过期删除缓存数据(可以根据业务优化需要是否返回当前过期数据)
  • 在每个记录缓存监控数据
  1. func (s *segment) getWarpEntry(key string, hashKey uint64) ([]byte,error) {
  2. index, ok := s.hashmap[hashKey]
  3. if !ok {
  4. s.stats.miss()
  5. return nil, ErrEntryNotFound
  6. }
  7. entry, err := s.entries.Get(int(index))
  8. if err != nil{
  9. s.stats.miss()
  10. return nil, err
  11. }
  12. if entry == nil{
  13. s.stats.miss()
  14. return nil, ErrEntryNotFound
  15. }
  16.  
  17. if entryKey := readKeyFromEntry(entry); key != entryKey {
  18. s.stats.collision()
  19. return nil, ErrEntryNotFound
  20. }
  21. return entry, nil
  22. }
  23.  
  24. func (s *segment) get(key string, hashKey uint64) ([]byte, error) {
  25. currentTimestamp := s.clock.TimeStamp()
  26. entry, err := s.getWarpEntry(key, hashKey)
  27. if err != nil{
  28. return nil, err
  29. }
  30. res := readEntry(entry)
  31.  
  32. expireAt := int64(readExpireAtFromEntry(entry))
  33. if currentTimestamp - expireAt >= 0{
  34. _ = s.entries.Remove(int(s.hashmap[hashKey]))
  35. delete(s.hashmap, hashKey)
  36. return nil, ErrEntryNotFound
  37. }
  38. s.stats.hit(key)
  39.  
  40. return res, nil
  41. }

第七步:来个测试用例体验一下

先来个简单的测试用例测试一下:

  1. func (h *cacheTestSuite) TestSetAndGet() {
  2. cache, err := NewCache()
  3. assert.Equal(h.T(), nil, err)
  4. key := "asong"
  5. value := []byte("公众号:Golang梦工厂")
  6.  
  7. err = cache.Set(key, value)
  8. assert.Equal(h.T(), nil, err)
  9.  
  10. res, err := cache.Get(key)
  11. assert.Equal(h.T(), nil, err)
  12. assert.Equal(h.T(), value, res)
  13. h.T().Logf("get value is %s", string(res))
  14. }

运行结果:

  1. === RUN TestCacheTestSuite
  2. === RUN TestCacheTestSuite/TestSetAndGet
  3. cache_test.go:33: get value is 公众号:Golang梦工厂
  4. --- PASS: TestCacheTestSuite (0.00s)
  5. --- PASS: TestCacheTestSuite/TestSetAndGet (0.00s)
  6. PASS

大功告成,基本功能通了,剩下就是跑基准测试、优化、迭代了(不在文章赘述了,可以关注github仓库最新动态)。

参考文章

  • https://github.com/allegro/bigcache
  • https://github.com/VictoriaMetrics/fastcache
  • https://github.com/coocood/freecache
  • https://github.com/patrickmn/go-cache

总结

实现篇到这里就结束了,但是这个项目的编码仍未结束,我会继续以此版本为基础不断迭代优化,该本地缓存的优点:

  • 实现简单、提供给用户的方法简单易懂
  • 使用二维切片作为存储结构,避免了不能删除底层数据的缺点,也在一定程度上避免了"虫洞"问题。
  • 测试用例齐全,适合作为小白的入门项目

待优化点:

  • 没有使用高效的缓存淘汰算法,可能会导致热点数据被频繁删除
  • 定时删除过期数据会导致锁持有时间过长,需要优化
  • 关闭缓存实例需要优化处理方式
  • 根据业务场景进行优化(特定业务场景)

迭代点:

  • 添加异步加载缓存功能
  • ...... (思考中)

本文代码已经上传到github:https://github.com/asong2020/go-localcache

好啦,本文到这里就结束了,我是asong,我们下期见。

原文链接:https://mp.weixin.qq.com/s/11m4m0YA0wPut5alVUu-Ew

延伸 · 阅读

精彩推荐
  • Golanggolang 通过ssh代理连接mysql的操作

    golang 通过ssh代理连接mysql的操作

    这篇文章主要介绍了golang 通过ssh代理连接mysql的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    a165861639710342021-03-08
  • GolangGolang中Bit数组的实现方式

    Golang中Bit数组的实现方式

    这篇文章主要介绍了Golang中Bit数组的实现方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    天易独尊11682021-06-09
  • Golanggolang的httpserver优雅重启方法详解

    golang的httpserver优雅重启方法详解

    这篇文章主要给大家介绍了关于golang的httpserver优雅重启的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,...

    helight2992020-05-14
  • Golanggolang json.Marshal 特殊html字符被转义的解决方法

    golang json.Marshal 特殊html字符被转义的解决方法

    今天小编就为大家分享一篇golang json.Marshal 特殊html字符被转义的解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    李浩的life12792020-05-27
  • GolangGolang通脉之数据类型详情

    Golang通脉之数据类型详情

    这篇文章主要介绍了Golang通脉之数据类型,在编程语言中标识符就是定义的具有某种意义的词,比如变量名、常量名、函数名等等,Go语言中标识符允许由...

    4272021-11-24
  • Golanggo语言制作端口扫描器

    go语言制作端口扫描器

    本文给大家分享的是使用go语言编写的TCP端口扫描器,可以选择IP范围,扫描的端口,以及多线程,有需要的小伙伴可以参考下。 ...

    脚本之家3642020-04-25
  • Golanggo日志系统logrus显示文件和行号的操作

    go日志系统logrus显示文件和行号的操作

    这篇文章主要介绍了go日志系统logrus显示文件和行号的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    SmallQinYan12302021-02-02
  • Golanggolang如何使用struct的tag属性的详细介绍

    golang如何使用struct的tag属性的详细介绍

    这篇文章主要介绍了golang如何使用struct的tag属性的详细介绍,从例子说起,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看...

    Go语言中文网11352020-05-21