### 核心功能详解 #### 配置选项 ACache允许开发者灵活配置缓存的时间、大小和数量限制。例如,可以通过以下代码片段设置缓存的有效时间和最大缓存大小: ```java public static final int TIME_HOUR = 60 * 60; // 缓存1小时 public static final int TIME_MINUTE = 60; // 缓存1分钟 public static final int TIME_DAY = TIME_HOUR * 12; // 缓存半天(12小时) private static final int MAX_SIZE = 1000 * 1000 * 50; // 最大50MB private static final int MAX_COUNT = Integer.MAX_VALUE; // 不限制缓存项数 ```
#### 获取ACache实例 要使用ACache,首先需要获取其实例。可以通过以下几种方式获取: ```java public static ACache get(Context ctx) public static ACache get(Context ctx, String cacheName) public static ACache get(File cacheDir) public static ACache get(Context ctx, long max_size, int max_count) ``` 每种方法都允许根据不同的需求定制缓存策略。
#### ACacheManager实现 ACache的核心管理逻辑由`ACacheManager`类负责,它处理缓存文件的创建、大小计算和超时清理等功能。以下是`ACacheManager`的部分实现: ```java public class ACacheManager { private final AtomicLong cacheSize; private final AtomicInteger cacheCount; private final long sizeLimit; private final int countLimit; private final Map lastUsageDates = Collections.synchronizedMap(new HashMap<>()); protected File cacheDir;
public ACacheManager(File cacheDir, long sizeLimit, int countLimit) { this.cacheDir = cacheDir; this.sizeLimit = sizeLimit; this.countLimit = countLimit; cacheSize = new AtomicLong(); cacheCount = new AtomicInteger(); calculateCacheSizeAndCacheCount(); }
private void calculateCacheSizeAndCacheCount() { new Thread(() -> { int size = 0; int count = 0; File[] cachedFiles = cacheDir.listFiles(); if (cachedFiles != null) { for (File cachedFile : cachedFiles) { size += calculateSize(cachedFile); count++; lastUsageDates.put(cachedFile, cachedFile.lastModified()); } cacheSize.set(size); cacheCount.set(count); } }).start(); }