SetWithTimestamp 设置缓存,并指定最后修改时间
(key string, data []byte, ttl time.Duration, lastModified time.Time)
| 39 | |
| 40 | // SetWithTimestamp 设置缓存,并指定最后修改时间 |
| 41 | func (c *MemoryCache) SetWithTimestamp(key string, data []byte, ttl time.Duration, lastModified time.Time) { |
| 42 | c.mutex.Lock() |
| 43 | defer c.mutex.Unlock() |
| 44 | |
| 45 | // 如果已存在,先减去旧项的大小 |
| 46 | if item, exists := c.items[key]; exists { |
| 47 | c.currSize -= int64(item.size) |
| 48 | } |
| 49 | |
| 50 | // 创建新的缓存项 |
| 51 | now := time.Now() |
| 52 | item := &memoryCacheItem{ |
| 53 | data: data, |
| 54 | expiry: now.Add(ttl), |
| 55 | lastUsed: now, |
| 56 | lastModified: lastModified, |
| 57 | size: len(data), |
| 58 | } |
| 59 | |
| 60 | // 检查是否需要清理空间 |
| 61 | if len(c.items) >= c.maxItems || c.currSize+int64(len(data)) > c.maxSize { |
| 62 | c.evict() |
| 63 | } |
| 64 | |
| 65 | // 存储新项 |
| 66 | c.items[key] = item |
| 67 | c.currSize += int64(len(data)) |
| 68 | } |
| 69 | |
| 70 | // 获取缓存 |
| 71 | func (c *MemoryCache) Get(key string) ([]byte, bool) { |
no test coverage detected