关于go:go内存缓存BigCache源码阅读BytesQueue-实现

6次阅读

共计 1216 个字符,预计需要花费 4 分钟才能阅读完成。

一、介绍
BytesQueue 构造,是 bigcache 真正数据存储的中央。

在 bigCache 中,所有的 value 都是存在一个 BytesQueue 中的,从实现可知,所有的用户存储数据经由序列化后存入 array []byte

// BytesQueue is a non-thread safe queue type of fifo based on bytes array.
// BytesQueue 是基于字节数组的非线程平安队列类型的 FIFO。// For every push operation index of entry is returned. It can be used to read the entry later
// 对于每个推送操作索引,都会返回。它可用于稍后浏览条目。type BytesQueue struct {
    full         bool
    array        []byte // 真正存储数据的中央
    capacity     int    // array 的容量
    maxCapacity  int    // array 可申请的最大容量
    head         int
    tail         int // 下次能够插入 item 的地位
    count        int // 以后插入的 item 数量
    rightMargin  int
    headerBuffer []byte // 插入前做长期 buffer 所用(slice-copy)verbose      bool   // 打印 log 开关
}

初始化 BytesQueue 的办法为

func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue {
    return &BytesQueue{array:        make([]byte, capacity), // 真正存储数据的中央,长度为 capacity,间接初始化每个值
        capacity:     capacity,
        maxCapacity:  maxCapacity,
        headerBuffer: make([]byte, binary.MaxVarintLen32),
        tail:         leftMarginIndex,
        head:         leftMarginIndex,
        rightMargin:  leftMarginIndex,
        verbose:      verbose,
    }
}

咱们通过保护上面几个变量来实现存储位移及标识:
head:起始地位(也能够了解为,以后最老的数据的地位,删除的逻辑从这个地位开始)
tail:下次能够插入 item 的地位
capacity:标识 array 的容量
count:以后曾经插入的 item 的数量
maxCapacity:标识 array 能够申请的最大容量
rightMargin:用于标识队列中最初一个元素的地位,是一个相对地位。
leftMarginIndex:常量,值为 1,标识队列的结尾地位(0 号不必)

留神,head 和 tail 以及 rightMargin 的初始值都是 leftMarginIndex。BytesQueue 应用 []byte 类型来模仿队列,插入数据从 tail 地位,删除数据从 head 地位。为规范的 FIFO 队列。

正文完
 0