Cache Cache 是一个接口,主要方法有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /** * 通过key得到缓存的实体对象 */ public Entry get(String key); /** * 保存一个请求的实体对象 */ public void put(String key, Entry entry); /** * 初始化,将硬盘上的缓存文件的首部信息加载到内存中,方便后面查询缓存是否存在 */ public void initialize(); /** * 根据key移除一个缓存实体 */ public void remove(String key); /** * 清除缓存 */ public void clear();
还有一个静态内部类 Entry:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 public static class Entry { /** * 请求返回的数据,(Body 实体) */ public byte[] data; /** * Http 响应首部中用于缓存新鲜度验证的 ETag */ public String etag; /** * Http 响应首部中的响应产生时间 */ public long serverDate; /** 请求返回的数据,在服务端的最近修改时间 */ public long lastModified; /** * 缓存的过期时间 */ public long ttl; /** * 缓存的新鲜时间 */ public long softTtl; /** * http的相应头部 */ public Map<String, String> responseHeaders = Collections.emptyMap(); /** * 判断是否到期,过期缓存不能继续使用 */ public boolean isExpired() { return this.ttl < System.currentTimeMillis(); } /** * 判断是否需要刷新数据(判断缓存是否新鲜),不新鲜的缓存需要发到服务端做新鲜度的检测 */ public boolean refreshNeeded() { return this.softTtl < System.currentTimeMillis(); } }
有两个实现子类,NoCache就是空实现,这里不做分析了;DiskBasedCache就是在Volley.java初始化RequestQueue的时候传进去的mCache对象!
DiskBasedCache DiskBasedCache是Volley中负责硬盘缓存的类。
获取缓存的数据的大体步骤。 第一步: 当NetWorkDispatcher的run方法开始执行(NetWorkDispatcher是Thread类的子类),进入循环,从网络请求队列中取出一个请求对象,执行网络请求。 第二步: 将从服务器得到的数据转换为Response对象(此对象代表一个网络响应)。 第三步: 根据 请求对象是否要求缓存(在新建Request的时候设置的值)来决定是否将响应数据写入缓存中。 以上三步得到缓存数据。缓存包括:** 网络响应的响应正文和头信息**。
得到缓存数据以后就可以调用Cache类或者其子类的put方法将缓存信息写入SD卡(Volley并没有做内存的缓存而是直接写入到磁盘文件)。在请求数据之前,就可以根据需要调用get方法来从SD卡取出之前缓存的数据。
在Volley中,为了描述缓存文件,将缓存文件的一些重要属性—缓存文件的大小,缓存对应的URL,服务器的响应时间,网络延迟和缓存的新鲜度作为头信息组成CacheHeader 对象写入到缓存文件中,并将响应正文写入CacheHeader后面,组成一个缓存文件 。在取缓存的时候,根据内存中的CacheHeader对象(缓存文件属性的封装类)的map集合(此map的key为待请求的URL,Value是CacheHeader对象)判断此请求对象是否有缓存。如果有缓存的话,将缓存读出来,封装成Entry(缓存属性和数据的封装类),从而恢复成response对象。一写一读就完成了缓存的写入和取出操作。
源码分析,首先分析成员变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 private final Map<String, CacheHeader> mEntries = new LinkedHashMap<String, CacheHeader>(16, .75f, true); private long mTotalSize = 0; private final File mRootDirectory; private final int mMaxCacheSizeInBytes; private static final int DEFAULT_DISK_USAGE_BYTES = 5 * 1024 * 1024; private static final float HYSTERESIS_FACTOR = 0.9f; private static final int CACHE_MAGIC = 0x20150306;
mEntries,一个用来判断缓存是否存在的map,key为url,value为url对应的响应数据的首部信息封装类CacheHeader。
mTotalSize,当前已经缓存文件的总的大小。
DEFAULT_DISK_USAGE_BYTES,缓存的默认大小。
CACHE_MAGIC,魔数,写在缓存文件的头部,用来表示这个文件是个缓存文件。读取的时候先读取这个魔数,如果和定义的CACHE_MAGIC不对应的话,说明这不是一个缓存文件,丢弃掉这个文件。
构造方法,一共两个构造方法:
1 2 3 4 5 6 7 8 public DiskBasedCache(File rootDirectory, int maxCacheSizeInBytes) { mRootDirectory = rootDirectory; mMaxCacheSizeInBytes = maxCacheSizeInBytes; } public DiskBasedCache(File rootDirectory) { this(rootDirectory, DEFAULT_DISK_USAGE_BYTES); }
构造方法完成了对缓存目录和缓存大小的设置。
put方法的源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Override public synchronized void put(String key, Entry entry) { pruneIfNeeded(entry.data.length); // 检测是否缓存已满,若时则删除一些缓存! File file = getFileForKey(key); // 创建缓存文件 try { FileOutputStream fos = new FileOutputStream(file); CacheHeader e = new CacheHeader(key, entry); // 构造CacheHeader对象 e.writeHeader(fos); // 写入头信息 fos.write(entry.data); // 写入主体信息 fos.close(); putEntry(key, e); // 保存到map中 return; } catch (IOException e) { } boolean deleted = file.delete(); // ??? if (!deleted) { VolleyLog.d("Could not clean up file %s", file.getAbsolutePath()); } }
方法体的第一行代码的作用是进行缓存的管理,检测是否缓存已满,若时则删除一些缓存。这里先知道作用即可,后面会对源码进行分析。
1 pruneIfNeeded(entry.data.length);
接下来,根据请求Url新建缓存文件。
1 File file = getFileForKey(key); // 创建缓存文件
1 2 3 public File getFileForKey(String key) { return new File(mRootDirectory, getFilenameForKey(key)); }
1 2 3 4 5 6 7 // 从这里可以看出,缓存文件的名称是由url地址前半部分的hashcode和后半部分的hashcode拼接而成!之所以这么做是为了防止缓存文件名发生碰撞。 private String getFilenameForKey(String key) { int firstHalfLength = key.length() / 2; String localFilename = String.valueOf(key.substring(0, firstHalfLength).hashCode()); localFilename += String.valueOf(key.substring(firstHalfLength).hashCode()); return localFilename; }
然后使用字节流将数据写入该文件中。注意代码将写头部信息和写数据是分开的,这里是因为头部信息是有一定的结构,必须按照头信息的格式写入文件。关于头信息怎么写的,建议阅读:。
1 2 3 4 5 FileOutputStream fos = new FileOutputStream(file); CacheHeader e = new CacheHeader(key, entry); // 构造CacheHeader对象 e.writeHeader(fos); // 写入头信息 fos.write(entry.data); // 写入主体信息 fos.close();
写完之后,将代表缓存信息的CacheHeader放入内存方便以后对缓存的检索。
1 putEntry(key, e); // 保存到map中
如果在写文件中遇到异常,删除缓存文件。如果删除不成功,打Log。
1 2 3 4 5 6 7 8 9 10 try { .... putEntry(key, e); // 保存到map中 return; } catch (IOException e) { } boolean deleted = file.delete(); // ??? if (!deleted) { VolleyLog.d("Could not clean up file %s", file.getAbsolutePath()); }
get方法的源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 @Override public synchronized Entry get(String key) { CacheHeader entry = mEntries.get(key); // if the entry does not exist, return. if (entry == null) { return null; } File file = getFileForKey(key); CountingInputStream cis = null; try { cis = new CountingInputStream(new FileInputStream(file)); CacheHeader.readHeader(cis); // eat header byte[] data = streamToBytes(cis, (int) (file.length() - cis.bytesRead)); return entry.toCacheEntry(data); } catch (IOException e) { VolleyLog.d("%s: %s", file.getAbsolutePath(), e.toString()); remove(key); return null; } finally { if (cis != null) { try { cis.close(); } catch (IOException ioe) { return null; } } } }
首先根据内存中的头信息,判断是否有该key的缓存,没有的话直接返回null,有的话执行if后面的代码。
1 2 3 4 5 CacheHeader entry = mEntries.get(key); // if the entry does not exist, return. if (entry == null) { return null; }
首先得到缓存文件,接着创建一个字节输入流的包装类CountingInputStream,此类有一个功能–记住已经读取的字节数,从而方便的读取头信息这类有结构的数据 。
1 2 3 4 5 6 7 8 9 10 File file = getFileForKey(key); CountingInputStream cis = null; try { cis = new CountingInputStream(new FileInputStream(file)); .... } catch (IOException e) { .... } finally { .... }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 private static class CountingInputStream extends FilterInputStream { private int bytesRead = 0; private CountingInputStream(InputStream in) { super(in); } @Override public int read() throws IOException { int result = super.read(); if (result != -1) { bytesRead++; } return result; } @Override public int read(byte[] buffer, int offset, int count) throws IOException { int result = super.read(buffer, offset, count); if (result != -1) { bytesRead += result; } return result; } }
接着用输入流的包装类CountingInputStream读取缓存文件,将读取到的头信息和读取到的数据组成entry对象返回。与put过程一样,这里也会涉及到头的处理,包括缓存的校验。
1 2 3 CacheHeader.readHeader(cis); // eat header byte[] data = streamToBytes(cis, (int) (file.length() - cis.bytesRead)); return entry.toCacheEntry(data);
1 2 3 4 5 6 7 8 9 10 11 12 private static byte[] streamToBytes(InputStream in, int length) throws IOException { byte[] bytes = new byte[length]; int count; int pos = 0; while (pos < length && ((count = in.read(bytes, pos, length - pos)) != -1)) { pos += count; } if (pos != length) { throw new IOException("Expected " + length + " bytes, read " + pos + " bytes"); } return bytes; }
接下来我们分析pruneIfNeeded方法,pruneIfNeeded方法的作用是判断待写入文件写入之后是否会超出缓存的最大值(默认5M)。如果超出,就删除掉之前的缓存数据。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 private void pruneIfNeeded(int neededSpace) { if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes) { return; } if (VolleyLog.DEBUG) { VolleyLog.v("Pruning old cache entries."); } long before = mTotalSize; int prunedFiles = 0; long startTime = SystemClock.elapsedRealtime(); Iterator<Map.Entry<String, CacheHeader>> iterator = mEntries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, CacheHeader> entry = iterator.next(); CacheHeader e = entry.getValue(); boolean deleted = getFileForKey(e.key).delete(); if (deleted) { mTotalSize -= e.size; } else { VolleyLog.d("Could not delete cache entry for key=%s, filename=%s", e.key, getFilenameForKey(e.key)); } iterator.remove(); prunedFiles++; if ((mTotalSize + neededSpace) < mMaxCacheSizeInBytes * HYSTERESIS_FACTOR) { break; } } if (VolleyLog.DEBUG) { VolleyLog.v("pruned %d files, %d bytes, %d ms", prunedFiles, (mTotalSize - before), SystemClock.elapsedRealtime() - startTime); } }
代码的主要逻辑在 CacheHeader组成的map的遍历,然后找到头信息所指的缓存文件,删除之。注意看这里的map:
1 2 private final Map<String, CacheHeader> mEntries = new LinkedHashMap<String, CacheHeader>(16, .75f, true);
mEntries,是一个LinkedHashMap,将构造方法中的第三参数accessOrder设置成了true,可以使遍历顺序和访问顺序一致,其内部双向链表将会按照近期最少访问到近期最多访问的顺序排列Entry对象,也就是实现了LRU。 接着再看下initialize()方法,这个方法的作用是,扫描缓存目录得到所有缓存数据摘要信息放入内存方便检索。源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @Override public synchronized void initialize() { if (!mRootDirectory.exists()) { if (!mRootDirectory.mkdirs()) { VolleyLog.e("Unable to create cache dir %s", mRootDirectory.getAbsolutePath()); } return; } File[] files = mRootDirectory.listFiles(); if (files == null) { return; } for (File file : files) { BufferedInputStream fis = null; try { fis = new BufferedInputStream(new FileInputStream(file)); CacheHeader entry = CacheHeader.readHeader(fis); entry.size = file.length(); putEntry(entry.key, entry); } catch (IOException e) { if (file != null) { file.delete(); } } finally { try { if (fis != null) { fis.close(); } } catch (IOException ignored) { } } } }
1 2 3 4 5 6 7 8 9 private void putEntry(String key, CacheHeader entry) { if (!mEntries.containsKey(key)) { mTotalSize += entry.size; } else { CacheHeader oldEntry = mEntries.get(key); mTotalSize += (entry.size - oldEntry.size); } mEntries.put(key, entry); }
1 2 3 4 5 6 7 private void removeEntry(String key) { CacheHeader entry = mEntries.get(key); if (entry != null) { mTotalSize -= entry.size; mEntries.remove(key); } }
最后看下clear方法:
1 2 3 4 5 6 7 8 9 10 11 12 @Override public synchronized void clear() { File[] files = mRootDirectory.listFiles(); if (files != null) { for (File file : files) { file.delete(); } } mEntries.clear(); mTotalSize = 0; VolleyLog.d("Cache cleared."); }
至此,DiskBasedCache源码介绍完毕。
参考链接:
Volley的cache之硬盘缓存–DiskBasedCache (作者的其他博文也值得学习)Volley 源码解析 Volley 源码解析 Volley源码解读
Java_io体系之FilterInputStream/FilterOutputStream简介、走进源码及示例——07
上一篇:Volley-CacheDispatcher源码解析
下一篇:Volley-DiskBasedCache的内部类CacheHeader的源码分析