Set 设置缓存
(key string, data []byte, ttl time.Duration)
| 112 | |
| 113 | // Set 设置缓存 |
| 114 | func (c *DiskCache) Set(key string, data []byte, ttl time.Duration) error { |
| 115 | c.mutex.Lock() |
| 116 | defer c.mutex.Unlock() |
| 117 | |
| 118 | // 如果已存在,先减去旧项的大小 |
| 119 | if meta, exists := c.metadata[key]; exists { |
| 120 | c.currSize -= int64(meta.Size) |
| 121 | // 删除旧文件 |
| 122 | filename := c.getFilename(key) |
| 123 | os.Remove(filepath.Join(c.path, filename)) |
| 124 | os.Remove(filepath.Join(c.path, filename+".meta")) |
| 125 | } |
| 126 | |
| 127 | // 检查空间 |
| 128 | maxSize := int64(c.maxSizeMB) * 1024 * 1024 |
| 129 | if c.currSize+int64(len(data)) > maxSize { |
| 130 | // 清理空间 |
| 131 | c.evictLRU(int64(len(data))) |
| 132 | } |
| 133 | |
| 134 | // 获取文件名 |
| 135 | filename := c.getFilename(key) |
| 136 | filePath := filepath.Join(c.path, filename) |
| 137 | |
| 138 | // 确保目录存在(防止外部删除缓存目录) |
| 139 | if err := os.MkdirAll(c.path, 0755); err != nil { |
| 140 | return fmt.Errorf("创建缓存目录失败: %v", err) |
| 141 | } |
| 142 | |
| 143 | // 写入文件 |
| 144 | if err := ioutil.WriteFile(filePath, data, 0644); err != nil { |
| 145 | return err |
| 146 | } |
| 147 | |
| 148 | // 创建元数据 |
| 149 | now := time.Now() |
| 150 | meta := &diskCacheMetadata{ |
| 151 | Key: key, |
| 152 | Expiry: now.Add(ttl), |
| 153 | LastUsed: now, |
| 154 | LastModified: now, // 设置最后修改时间 |
| 155 | Size: len(data), |
| 156 | } |
| 157 | |
| 158 | // 保存元数据 |
| 159 | if err := c.saveMetadata(key, meta); err != nil { |
| 160 | // 如果元数据保存失败,删除数据文件 |
| 161 | os.Remove(filePath) |
| 162 | return err |
| 163 | } |
| 164 | |
| 165 | // 更新内存中的元数据 |
| 166 | c.metadata[key] = meta |
| 167 | c.currSize += int64(len(data)) |
| 168 | |
| 169 | return nil |
| 170 | } |
| 171 |
no test coverage detected