99 lines
2.7 KiB
Markdown
99 lines
2.7 KiB
Markdown
|
|
# ResourceCache
|
|||
|
|
|
|||
|
|
**命名空间**: `XCEngine::Resources`
|
|||
|
|
|
|||
|
|
**类型**: `class`
|
|||
|
|
|
|||
|
|
**描述**: 资源缓存管理类,使用 LRU(最近最少使用)策略管理内存压力下的资源驱逐。
|
|||
|
|
|
|||
|
|
## 概述
|
|||
|
|
|
|||
|
|
`ResourceCache` 实现了资源的内存缓存管理。它跟踪每个资源的访问时间和访问次数,在内存压力下自动驱逐最近最少使用的资源,确保内存使用不超过预算。
|
|||
|
|
|
|||
|
|
## 公共方法
|
|||
|
|
|
|||
|
|
### 生命周期
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `ResourceCache()` | 默认构造函数 |
|
|||
|
|
| `~ResourceCache()` | 析构函数 |
|
|||
|
|
|
|||
|
|
### 缓存操作
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `void Add(ResourceGUID guid, IResource* resource)` | 添加资源到缓存 |
|
|||
|
|
| `void Remove(ResourceGUID guid)` | 从缓存中移除资源 |
|
|||
|
|
| `IResource* Find(ResourceGUID guid) const` | 查找资源 |
|
|||
|
|
| `void Touch(ResourceGUID guid)` | 更新资源的访问时间(LRU) |
|
|||
|
|
|
|||
|
|
### 内存管理
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `size_t GetSize() const` | 获取缓存中资源数量 |
|
|||
|
|
| `size_t GetMemoryUsage() const` | 获取缓存内存使用量(字节) |
|
|||
|
|
| `void SetMemoryBudget(size_t bytes)` | 设置内存预算 |
|
|||
|
|
| `size_t GetMemoryBudget() const` | 获取内存预算 |
|
|||
|
|
| `void OnMemoryPressure(size_t requiredBytes)` | 内存压力回调,驱逐资源以释放空间 |
|
|||
|
|
| `void OnZeroRefCount(ResourceGUID guid)` | 当引用计数为零时的回调 |
|
|||
|
|
|
|||
|
|
### 缓存控制
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `void Flush()` | 清空缓存,释放所有资源 |
|
|||
|
|
| `void Clear()` | 清空缓存但不释放资源 |
|
|||
|
|
|
|||
|
|
### LRU 信息
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `Containers::Array<ResourceGUID> GetLRUList(size_t count) const` | 获取最近最少使用的 GUID 列表 |
|
|||
|
|
|
|||
|
|
## CacheEntry 结构体
|
|||
|
|
|
|||
|
|
缓存条目结构体。
|
|||
|
|
|
|||
|
|
| 成员 | 类型 | 描述 |
|
|||
|
|
|------|------|------|
|
|||
|
|
| `resource` | `IResource*` | 资源指针 |
|
|||
|
|
| `guid` | `ResourceGUID` | 全局唯一标识符 |
|
|||
|
|
| `memorySize` | `size_t` | 内存大小 |
|
|||
|
|
| `lastAccessTime` | `Core::uint64` | 上次访问时间戳 |
|
|||
|
|
| `accessCount` | `Core::uint32` | 访问次数 |
|
|||
|
|
|
|||
|
|
### 静态方法
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `static Core::uint64 GetCurrentTick()` | 获取当前时间戳 |
|
|||
|
|
|
|||
|
|
## 使用示例
|
|||
|
|
|
|||
|
|
```cpp
|
|||
|
|
ResourceCache cache;
|
|||
|
|
cache.SetMemoryBudget(512 * 1024 * 1024); // 512MB 预算
|
|||
|
|
|
|||
|
|
// 添加资源
|
|||
|
|
cache.Add(guid, resource);
|
|||
|
|
|
|||
|
|
// 访问资源(更新 LRU)
|
|||
|
|
cache.Touch(guid);
|
|||
|
|
|
|||
|
|
// 查找资源
|
|||
|
|
IResource* res = cache.Find(guid);
|
|||
|
|
|
|||
|
|
// 内存压力时自动驱逐
|
|||
|
|
cache.OnMemoryPressure(100 * 1024 * 1024); // 需要 100MB
|
|||
|
|
|
|||
|
|
// 获取最少使用的资源
|
|||
|
|
auto lruList = cache.GetLRUList(10);
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 相关文档
|
|||
|
|
|
|||
|
|
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
|
|||
|
|
- [IResource](./resources-iresource.md) - 资源基类
|