Get 获取缓存
(ctx context.Context, key string)
| 129 | |
| 130 | // Get 获取缓存 |
| 131 | func (c *ToolCache) Get(ctx context.Context, key string) (any, bool) { |
| 132 | if !c.config.Enabled { |
| 133 | return nil, false |
| 134 | } |
| 135 | |
| 136 | // 先尝试内存缓存 |
| 137 | if c.config.Strategy == CacheStrategyMemory || c.config.Strategy == CacheStrategyBoth { |
| 138 | if value, ok := c.getFromMemory(key); ok { |
| 139 | c.stats.Hits++ |
| 140 | return value, true |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | // 再尝试文件缓存 |
| 145 | if c.config.Strategy == CacheStrategyFile || c.config.Strategy == CacheStrategyBoth { |
| 146 | if value, ok := c.getFromFile(key); ok { |
| 147 | c.stats.Hits++ |
| 148 | |
| 149 | // 如果是双层缓存,将文件缓存加载到内存 |
| 150 | if c.config.Strategy == CacheStrategyBoth { |
| 151 | c.setToMemory(key, value, c.config.TTL) |
| 152 | } |
| 153 | |
| 154 | return value, true |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | c.stats.Misses++ |
| 159 | return nil, false |
| 160 | } |
| 161 | |
| 162 | // Set 设置缓存 |
| 163 | func (c *ToolCache) Set(ctx context.Context, key string, value any, ttl time.Duration) error { |