图片缓存配置说明
📋 配置文件位置
config/image-cache.config.uts
⚙ ️ 默认配置
export const DEFAULT_IMAGE_CACHE_CONFIG: ImageCacheConfig = {
enabled: false, // ⚠️ 默认禁用,提升性能
expiryTime: 7 * 24 * 60 * 60 * 1000, // 7天
maxCacheCount: 100
};
🎯 为什么默认禁用?
1. 性能优化
- 避免低端机 Storage 阻塞导致 ANR(应用无响应)
- 减少主线程负担,提升页面加载速度
- 降低内存占用
2. 用户体验
- 快速启动,无白屏等待
- 流畅的页面切换
- 减少卡顿和掉帧
3. 资源节省
- 减少 Storage 空间占用
- 降低网络请求(虽然禁用了缓存,但图片本身会从 CDN 加载)
🔧 如何启用缓存
方法 1:修改配置文件(全局生效)
编辑 config/image-cache.config.uts:
export const DEFAULT_IMAGE_CACHE_CONFIG: ImageCacheConfig = {
enabled: true, // ✅ 改为 true 启用
expiryTime: 7 * 24 * 60 * 60 * 1000,
maxCacheCount: 100
};
方法 2:运行时动态修改(推荐)
在设置页面或应用启动时:
import imageCache from "@/services/cache/ImageCacheService.uts";
// 启用缓存
imageCache.setEnabled(true);
// 禁用缓存
imageCache.setEnabled(false);
方法 3:在代码中临时启用
import imageCache from "@/services/cache/ImageCacheService.uts";
// 临时启用(仅当前会话)
imageCache.updateConfig({
enabled: true,
expiryTime: 3 * 24 * 60 * 60 * 1000, // 3天
maxCacheCount: 50
});
📊 配置项说明
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
enabled |
boolean | false |
是否启用缓存 |
expiryTime |
number | 7天 |
缓存过期时间(毫秒) |
maxCacheCount |
number | 100 |
最大缓存数量 |
💡 使用建议
低端机(内存 < 2GB)
// 保持默认禁用
imageCache.setEnabled(false);
中高端机(内存 >= 4GB)
// 可以启用,但限制缓存数量
imageCache.updateConfig({
enabled: true,
maxCacheCount: 50, // 限制数量
expiryTime: 3 * 24 * 60 * 60 * 1000 // 缩短过期时间
});
离线场景需求强
// 完全启用,延长过期时间
imageCache.updateConfig({
enabled: true,
expiryTime: 30 * 24 * 60 * 60 * 1000, // 30天
maxCacheCount: 200
});
🔍 检查缓存状态
import imageCache from "@/services/cache/ImageCacheService.uts";
// 检查是否启用
const enabled = imageCache.isEnabled();
console.log('缓存状态:', enabled ? '已启用' : '已禁用');
// 获取统计信息
const stats = imageCache.getCacheStats();
console.log('缓存统计:', stats);
// {
// totalCount: 50, // 总缓存数
// validCount: 45, // 有效缓存数
// expiredCount: 5 // 过期缓存数
// }
🗑 ️ 清理缓存
import imageCache from "@/services/cache/ImageCacheService.uts";
// 清空所有缓存
imageCache.clearAllCache();
// 删除单个缓存
imageCache.removeCache('cache_key');
📝 注意事项
- 默认禁用是出于性能考虑 - 除非有明确的离线需求,否则建议保持禁用
- 启用后会增加 Storage 占用 - 注意监控存储空间
- 缓存会自动清理 - 过期或超出数量限制时自动删除
- 异步写入不阻塞 - 即使启用也不会影响主线程性能
🚀 最佳实践
// App.uvue 或 main.uts
import imageCache from "@/services/cache/ImageCacheService.uts";
import { isImageCacheEnabled } from "@/config/image-cache.config.uts";
onLaunch(() => {
// 根据设备性能决定是否启用
const deviceInfo = uni.getDeviceInfo();
if (isImageCacheEnabled()) {
// 配置已启用,可以根据设备调整参数
if (deviceInfo.memorySize < 2 * 1024) {
// 低端机:禁用
imageCache.setEnabled(false);
console.log('[性能优化] 低端机已禁用图片缓存');
} else {
// 中高端机:启用但限制数量
imageCache.updateConfig({
maxCacheCount: 50
});
console.log('[性能优化] 已启用图片缓存(限制50条)');
}
}
});
总结:默认禁用缓存是为了保证最佳性能,如需离线功能可按需启用。