diff --git a/internal/cache/file_cache.go b/internal/cache/file_cache.go index a65d30a..2b5c687 100644 --- a/internal/cache/file_cache.go +++ b/internal/cache/file_cache.go @@ -148,6 +148,17 @@ func (c *FileCache) Get(path string) (*FileEntry, bool) { return entry, true } + // 更新近似 LRU 访问时间(每 5 秒或超过 10% inactive 间隔才写,减少锁竞争) + const accessUpdateInterval = 5 * time.Second + if time.Since(entry.LastAccess) > accessUpdateInterval { + c.mu.Lock() + if e, ok := c.entries[path]; ok && e == entry { + e.LastAccess = time.Now() + c.lruList.MoveToFront(e.element) + } + c.mu.Unlock() + } + // 近似 LRU: 不更新 LastAccess/LRU 位置,直接返回 // 精确 LRU 由 Set/Delete/evict 操作保证 return entry, true diff --git a/internal/cache/file_cache_test.go b/internal/cache/file_cache_test.go new file mode 100644 index 0000000..a56a9c9 --- /dev/null +++ b/internal/cache/file_cache_test.go @@ -0,0 +1,24 @@ +// Package cache 提供文件缓存功能测试。 +package cache + +import ( + "testing" + "time" +) + +func TestFileCacheLastAccessUpdatedOnHit(t *testing.T) { + c := NewFileCache(1, 1<<20, 10*time.Second) + c.Set("/x", []byte("data"), 4, time.Now(), "text/plain") + + entry := c.entries["/x"] + before := entry.LastAccess + // 将访问时间设为过去,确保超过 accessUpdateInterval 阈值但不超过 inactive + entry.LastAccess = before.Add(-7 * time.Second) + + c.Get("/x") + after := c.entries["/x"].LastAccess + + if !after.After(before) { + t.Fatal("LastAccess was not updated on cache hit") + } +}