https://github.com/yangfuhai/ASimpleCache
杨神作品,大家最熟悉他的应该是afinal框架吧
ASimpleCache 是一个为android制定的 轻量级的 开源缓存框架。轻量到只有一个java文件(由十几个类精简而来)。
普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java对象,和 byte数据。
特色主要是:
1:轻,轻到只有一个JAVA文件。
2:可配置,可以配置缓存路径,缓存大小,缓存数量等。
3:可以设置缓存超时时间,缓存超时自动失效,并被删除。
4:支持多进程。
1、替换SharePreference当做配置文件
2、可以缓存网络请求数据,比如oschina的android客户端可以缓存http请求的新闻内容,缓存时间假设为1个小时,超时后自动失效,让客户端重新请求新的数据,减少客户端流量,同时减少服务器并发量。
3、您来说…
以下有个小的demo,希望您能喜欢:
<code class="hljs avrasm has-numbering">ACache mCache = ACache<span class="hljs-preprocessor">.get</span>(this)<span class="hljs-comment">;</span> mCache<span class="hljs-preprocessor">.put</span>(<span class="hljs-string">"test_key1"</span>, <span class="hljs-string">"test value"</span>)<span class="hljs-comment">;</span> mCache<span class="hljs-preprocessor">.put</span>(<span class="hljs-string">"test_key2"</span>, <span class="hljs-string">"test value"</span>, <span class="hljs-number">10</span>)<span class="hljs-comment">;//保存10秒,如果超过10秒去获取这个key,将为null</span> mCache<span class="hljs-preprocessor">.put</span>(<span class="hljs-string">"test_key3"</span>, <span class="hljs-string">"test value"</span>, <span class="hljs-number">2</span> * ACache<span class="hljs-preprocessor">.TIME</span>_DAY)<span class="hljs-comment">;//保存两天,如果超过两天去获取这个key,将为null</span></code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li></ul>
获取数据
<code class="hljs cs has-numbering">ACache mCache = ACache.<span class="hljs-keyword">get</span>(<span class="hljs-keyword">this</span>); String <span class="hljs-keyword">value</span> = mCache.getAsString(<span class="hljs-string">"test_key1"</span>);</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li></ul>
ASimpleCache里只有一个JAVA文件——ACache.java
首先我用思维导图制作了ACache类的详细结构图:
通过分析官方给的demo来驱动源码分析吧
以字符串存储为例(官方给的demo里给出了很多种数据读取的例子,其实方法相似),打开SaveStringActivity.java:
<code class="hljs java has-numbering"><span class="hljs-keyword">package</span> com.yangfuhai.asimplecachedemo; <span class="hljs-keyword">import</span> org.afinal.simplecache.ACache; <span class="hljs-keyword">import</span> android.app.Activity; <span class="hljs-keyword">import</span> android.os.Bundle; <span class="hljs-keyword">import</span> android.view.View; <span class="hljs-keyword">import</span> android.widget.EditText; <span class="hljs-keyword">import</span> android.widget.TextView; <span class="hljs-keyword">import</span> android.widget.Toast; <span class="hljs-javadoc">/** * *<span class="hljs-javadoctag"> @ClassName</span>: SaveStringActivity *<span class="hljs-javadoctag"> @Description</span>: 缓存string *<span class="hljs-javadoctag"> @Author</span> Yoson Hao *<span class="hljs-javadoctag"> @WebSite</span> www.haoyuexing.cn *<span class="hljs-javadoctag"> @Email</span> [email protected] *<span class="hljs-javadoctag"> @Date</span> 2013-8-7 下午9:59:43 * */</span> <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SaveStringActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Activity</span> {</span> <span class="hljs-keyword">private</span> EditText mEt_string_input; <span class="hljs-keyword">private</span> TextView mTv_string_res; <span class="hljs-keyword">private</span> ACache mCache; <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onCreate</span>(Bundle savedInstanceState) { <span class="hljs-keyword">super</span>.onCreate(savedInstanceState); setContentView(R.layout.activity_save_string); <span class="hljs-comment">// 初始化控件</span> initView(); mCache = ACache.get(<span class="hljs-keyword">this</span>); } <span class="hljs-javadoc">/** * 初始化控件 */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">initView</span>() { mEt_string_input = (EditText) findViewById(R.id.et_string_input); mTv_string_res = (TextView) findViewById(R.id.tv_string_res); } <span class="hljs-javadoc">/** * 点击save事件 * *<span class="hljs-javadoctag"> @param</span> v */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">save</span>(View v) { <span class="hljs-keyword">if</span> (mEt_string_input.getText().toString().trim().length() == <span class="hljs-number">0</span>) { Toast.makeText( <span class="hljs-keyword">this</span>, <span class="hljs-string">"Cuz u input is a nullcharacter ... So , when u press \"read\" , if do not show any result , plz don't be surprise"</span>, Toast.LENGTH_SHORT).show(); } <span class="hljs-comment">// mCache.put("testString", mEt_string_input.getText().toString());</span> mCache.put(<span class="hljs-string">"testString"</span>, mEt_string_input.getText().toString(),<span class="hljs-number">300</span>); } <span class="hljs-javadoc">/** * 点击read事件 * *<span class="hljs-javadoctag"> @param</span> v */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">read</span>(View v) { String testString = mCache.getAsString(<span class="hljs-string">"testString"</span>); <span class="hljs-keyword">if</span> (testString == <span class="hljs-keyword">null</span>) { Toast.makeText(<span class="hljs-keyword">this</span>, <span class="hljs-string">"String cache is null ..."</span>, Toast.LENGTH_SHORT) .show(); mTv_string_res.setText(<span class="hljs-keyword">null</span>); <span class="hljs-keyword">return</span>; } mTv_string_res.setText(testString); } <span class="hljs-javadoc">/** * 点击clear事件 * *<span class="hljs-javadoctag"> @param</span> v */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">clear</span>(View v) { mCache.remove(<span class="hljs-string">"testString"</span>); } } </code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li><li>83</li><li>84</li><li>85</li><li>86</li><li>87</li><li>88</li><li>89</li></ul>
可以看到缓存字符串的读取方法很简单!!!
那我们就从ACache.get()开始吧,其实查看上面的思维导图,ACache类的构造方法为private的,所以新建缓存实例只能通过ACache.get方式获取。
<code class="hljs cs has-numbering"> <span class="hljs-comment">//实例化应用程序场景缓存</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ACache <span class="hljs-title">get</span>(Context ctx) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">get</span>(ctx, <span class="hljs-string">"ACache"</span>); } <span class="hljs-comment">//新建缓存目录</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ACache <span class="hljs-title">get</span>(Context ctx, String cacheName) { <span class="hljs-comment">//新建文件夹,文件路径为应用场景缓存路径目录,文件夹名为ACache(new File()也可新建文件,带上后缀即可)</span> File f = <span class="hljs-keyword">new</span> File(ctx.getCacheDir(), cacheName); <span class="hljs-keyword">return</span> <span class="hljs-keyword">get</span>(f, MAX_SIZE, MAX_COUNT); } <span class="hljs-comment">//新建缓存实例,存入实例map,key为缓存目录+每次应用开启的进程id</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ACache <span class="hljs-title">get</span>(File cacheDir, <span class="hljs-keyword">long</span> max_zise, <span class="hljs-keyword">int</span> max_count) { <span class="hljs-comment">//返回key为缓存目录+每次应用开启的进程id的map的value值,赋给缓存实例manager</span> ACache manager = mInstanceMap.<span class="hljs-keyword">get</span>(cacheDir.getAbsoluteFile() + myPid()); <span class="hljs-keyword">if</span> (manager == <span class="hljs-keyword">null</span>) { <span class="hljs-comment">//缓存实例为空时,</span> manager = <span class="hljs-keyword">new</span> ACache(cacheDir, max_zise, max_count); mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);<span class="hljs-comment">//插入map</span> } <span class="hljs-keyword">return</span> manager; } </code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li></ul>
在调用ACache.get(Context)方法过程中,其实执行了三个get方法
(1)get(Context ctx)->(2)get(Context ctx, String cacheName)->(3)get(File cacheDir, long max_zise, int max_count)
在(2)中新建了缓存目录,路径为:
/data/data/app-package-name/cache/ACache
缓存大小MAX_SIZE和数量MAX_COUNT均由final变量控制。
其实最终调用(3)获取实例:
mInstanceMap的key为缓存目录+每次应用开启的进程id,value为ACache.
初次运行,mInstanceMap没有任何键值对,所以manager == null。故通过ACache构造方法构造新实例,最后将该实例引用存入mInstanceMap。
接下来我们来看看ACache构造方法:
<code class="hljs cs has-numbering"> <span class="hljs-comment">//ACache构造函数 为private私有(所以在其他类里获得实例只能通过get()方法)</span> <span class="hljs-keyword">private</span> <span class="hljs-title">ACache</span>(File cacheDir, <span class="hljs-keyword">long</span> max_size, <span class="hljs-keyword">int</span> max_count) { <span class="hljs-keyword">if</span> (!cacheDir.exists() && !cacheDir.mkdirs()) { <span class="hljs-comment">//缓存目录不存在并且无法创建时,抛出异常</span> <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"can't make dirs in "</span> + cacheDir.getAbsolutePath()); } mCache = <span class="hljs-keyword">new</span> ACacheManager(cacheDir, max_size, max_count);<span class="hljs-comment">//实例化ACacheManager内部类实例</span> } </code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li></ul>
缓存目录不存在并且无法创建时,抛出异常,否则实例化ACacheManager内部类实例(缓存管理器)。ACacheManager内部类的构造函数如下:
<code class="hljs cs has-numbering"> <span class="hljs-comment">//内部类ACacheManager的构造函数</span> <span class="hljs-keyword">private</span> <span class="hljs-title">ACacheManager</span>(File cacheDir, <span class="hljs-keyword">long</span> sizeLimit, <span class="hljs-keyword">int</span> countLimit) { <span class="hljs-keyword">this</span>.cacheDir = cacheDir; <span class="hljs-keyword">this</span>.sizeLimit = sizeLimit; <span class="hljs-keyword">this</span>.countLimit = countLimit; cacheSize = <span class="hljs-keyword">new</span> AtomicLong(); <span class="hljs-comment">//原子类实例cacheSize,不用加锁保证线程安全</span> cacheCount = <span class="hljs-keyword">new</span> AtomicInteger(); <span class="hljs-comment">//原子类实例cacheCount,不用加锁保证线程安全</span> calculateCacheSizeAndCacheCount(); }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>
构造函数得到原子类实例cacheSize和cacheCount,通过calculateCacheSizeAndCacheCount();方法计算cacheSize和cacheCount如下:
<code class="hljs java has-numbering"> <span class="hljs-javadoc">/** * 计算 cacheSize和cacheCount */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">calculateCacheSizeAndCacheCount</span>() { <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() { <span class="hljs-annotation">@Override</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span>() { <span class="hljs-comment">//int size = 0;</span> <span class="hljs-keyword">long</span> size = <span class="hljs-number">0</span>; <span class="hljs-comment">//这里long类型才对——by牧之丶</span> <span class="hljs-keyword">int</span> count = <span class="hljs-number">0</span>; File[] cachedFiles = cacheDir.listFiles(); <span class="hljs-comment">//返回缓存目录cacheDir下的文件数组</span> <span class="hljs-keyword">if</span> (cachedFiles != <span class="hljs-keyword">null</span>) { <span class="hljs-keyword">for</span> (File cachedFile : cachedFiles) { <span class="hljs-comment">//对文件数组遍历</span> size += calculateSize(cachedFile); count += <span class="hljs-number">1</span>; lastUsageDates.put(cachedFile, cachedFile.lastModified()); <span class="hljs-comment">//将缓存文件和最后修改时间插入map</span> } cacheSize.set(size); <span class="hljs-comment">//设置为给定值</span> cacheCount.set(count); <span class="hljs-comment">//设置为给定值</span> } } }).start(); }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li></ul>
calculateCacheSizeAndCacheCount方法中开启线程进行大小和数量的计算。计算完后存入cacheSize和cacheCount,cacheSize和cacheCount在内部类中定义为AtomicLong和AtomicInteger量子类,也就是线程安全的。其基本的特性就是在多线程环境下,当有多个线程同时执行这些类的实例包含的方法时,具有排他性,即当某个线程进入方法,执行其中的指令时,不会被其他线程打断,而别的线程就像自旋锁一样,一直等到该方法执行完成,才由JVM从等待队列中选择一个另一个线程进入。
到这里获取缓存实例工作完成,主要完成了如下工作:
接下来就是数据存取操作。
从上面的思维导图public method(各种数据的读写方法)中,有各种public的put和get等方法来缓存各种数据类型的数据。由上面的demo的put方法
mCache.put(“testString”, mEt_string_input.getText().toString(),300);我们找到原形:
<code class="hljs java has-numbering"> <span class="hljs-javadoc">/** * 保存 String数据 到 缓存中 * *<span class="hljs-javadoctag"> @param</span> key * 保存的key *<span class="hljs-javadoctag"> @param</span> value * 保存的String数据 *<span class="hljs-javadoctag"> @param</span> saveTime * 保存的时间,单位:秒 */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">put</span>(String key, String value, <span class="hljs-keyword">int</span> saveTime) { put(key, Utils.newStringWithDateInfo(saveTime, value)); } </code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li></ul>
这里的put方法可以指定缓存时间。调用他自身的另一个put方法:
<code class="hljs java has-numbering"><span class="hljs-javadoc">/** * 保存 String数据 到 缓存中 * *<span class="hljs-javadoctag"> @param</span> key * 保存的key *<span class="hljs-javadoctag"> @param</span> value * 保存的String数据 */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">put</span>(String key, String value) { File file = mCache.newFile(key); <span class="hljs-comment">//新建文件</span> BufferedWriter out = <span class="hljs-keyword">null</span>; <span class="hljs-comment">//缓冲字符输出流,作用是为其他字符输出流添加一些缓冲功能</span> <span class="hljs-keyword">try</span> { out = <span class="hljs-keyword">new</span> BufferedWriter(<span class="hljs-keyword">new</span> FileWriter(file), <span class="hljs-number">1024</span>); <span class="hljs-comment">//获取file字符流</span> out.write(value); <span class="hljs-comment">// 把value写入</span> } <span class="hljs-keyword">catch</span> (IOException e) { e.printStackTrace(); } <span class="hljs-keyword">finally</span> { <span class="hljs-keyword">if</span> (out != <span class="hljs-keyword">null</span>) { <span class="hljs-keyword">try</span> { out.flush(); out.close(); } <span class="hljs-keyword">catch</span> (IOException e) { e.printStackTrace(); } } mCache.put(file); <span class="hljs-comment">//更新cacheCount和cacheSize lastUsageDates插入新建文件和时间的键值对</span> } }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li></ul>
在put(String key, String value)方法中首先调用mCache.newFile(key)新建一个文件:
<code class="hljs cs has-numbering"> <span class="hljs-comment">//新建文件</span> <span class="hljs-keyword">private</span> File <span class="hljs-title">newFile</span>(String key) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> File(cacheDir, key.hashCode() + <span class="hljs-string">""</span>); <span class="hljs-comment">//新建文件,文件名为key的整型哈希码</span> }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li></ul>
新建的文件名为key的整型哈希码。回到put(String key, String value)中,然后通过out.write(value);将数据存入文件。最后调用mCache.put(file);进行ACacheManager实例的更新操作:
<code class="hljs cs has-numbering"> <span class="hljs-comment">//更新cacheCount和cacheSize lastUsageDates插入新建文件和时间的键值对</span> <span class="hljs-comment">//文件放入程序缓存后,统计缓存总量,总数,文件存放到文件map中(value值为文件最后修改时间,便于根据设置的销毁时间进行销毁)</span> <span class="hljs-comment">//缓存没有超过限制,则增加缓存总量,总数的数值</span> <span class="hljs-comment">//缓存超过限制,则减少缓存总量,总数的数值</span> <span class="hljs-comment">//通过removeNext方法找到最老文件的大小</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">put</span>(File file) { <span class="hljs-keyword">int</span> curCacheCount = cacheCount.<span class="hljs-keyword">get</span>(); <span class="hljs-comment">//获取数量 </span> <span class="hljs-keyword">while</span> (curCacheCount + <span class="hljs-number">1</span> > countLimit) { <span class="hljs-comment">//大于上限</span> <span class="hljs-keyword">long</span> freedSize = removeNext(); <span class="hljs-comment">//移除旧的文件,返回文件大小</span> cacheSize.addAndGet(-freedSize); <span class="hljs-comment">//更新cacheSize</span> curCacheCount = cacheCount.addAndGet(-<span class="hljs-number">1</span>);<span class="hljs-comment">//更新cacheCount</span> } cacheCount.addAndGet(<span class="hljs-number">1</span>);<span class="hljs-comment">//更新cacheCount</span> <span class="hljs-keyword">long</span> valueSize = calculateSize(file); <span class="hljs-comment">//计算文件大小</span> <span class="hljs-keyword">long</span> curCacheSize = cacheSize.<span class="hljs-keyword">get</span>(); <span class="hljs-comment">//获取当前缓存大小</span> <span class="hljs-keyword">while</span> (curCacheSize + valueSize > sizeLimit) { <span class="hljs-comment">//大于上限</span> <span class="hljs-keyword">long</span> freedSize = removeNext(); <span class="hljs-comment">//移除旧的文件,返回文件大小</span> curCacheSize = cacheSize.addAndGet(-freedSize); <span class="hljs-comment">//更新curCacheSize</span> } cacheSize.addAndGet(valueSize); <span class="hljs-comment">//更新cacheSize</span> Long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); <span class="hljs-comment">//设置文件最后修改时间</span> lastUsageDates.put(file, currentTime); <span class="hljs-comment">//插入map</span> }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li></ul>
分析完ACacheManager的put()后,我们回到put(key, Utils.newStringWithDateInfo(saveTime, value))
其中第二个参数value传入的是Utils.newStringWithDateInfo(saveTime, value),而newStringWithDateInfo是ACache的内部工具类的一个方法,在value内容前面加上了时间信息:
<code class="hljs cs has-numbering"> <span class="hljs-comment">//返回时间信息+value</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">newStringWithDateInfo</span>(<span class="hljs-keyword">int</span> second, String strInfo) { <span class="hljs-keyword">return</span> createDateInfo(second) + strInfo; }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li></ul>
返回拼接createDateInfo(second)和value的字符串。createDateInfo()如下:
<code class="hljs mel has-numbering"> <span class="hljs-comment">//时间信息</span> private static String createDateInfo(<span class="hljs-keyword">int</span> second) { String <span class="hljs-keyword">currentTime</span> = System.currentTimeMillis() + <span class="hljs-string">""</span>; <span class="hljs-keyword">while</span> (<span class="hljs-keyword">currentTime</span>.length() < <span class="hljs-number">13</span>) { <span class="hljs-comment">//小于13,前面补0</span> <span class="hljs-keyword">currentTime</span> = <span class="hljs-string">"0"</span> + <span class="hljs-keyword">currentTime</span>; } <span class="hljs-keyword">return</span> <span class="hljs-keyword">currentTime</span> + <span class="hljs-string">"-"</span> + second + mSeparator; <span class="hljs-comment">//当前时间-保存时间 </span> } </code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>
返回字符串格式为 当前时间-保存时间“ ”
由上面的demo的get方法mCache.getAsString(“testString”);我们找到原形:
<code class="hljs java has-numbering"> <span class="hljs-javadoc">/** * 读取 String数据 * *<span class="hljs-javadoctag"> @param</span> key *<span class="hljs-javadoctag"> @return</span> String 数据 */</span> <span class="hljs-keyword">public</span> String <span class="hljs-title">getAsString</span>(String key) { File file = mCache.get(key); <span class="hljs-comment">//获取文件</span> <span class="hljs-keyword">if</span> (!file.exists()) <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>; <span class="hljs-keyword">boolean</span> removeFile = <span class="hljs-keyword">false</span>; BufferedReader in = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { in = <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> FileReader(file)); String readString = <span class="hljs-string">""</span>; String currentLine; <span class="hljs-keyword">while</span> ((currentLine = in.readLine()) != <span class="hljs-keyword">null</span>) { <span class="hljs-comment">//逐行遍历</span> readString += currentLine; <span class="hljs-comment">//每行字符串连接</span> } <span class="hljs-keyword">if</span> (!Utils.isDue(readString)) { <span class="hljs-comment">//String数据未到期</span> <span class="hljs-keyword">return</span> Utils.clearDateInfo(readString);<span class="hljs-comment">//去除时间信息的字符串内容</span> } <span class="hljs-keyword">else</span> { removeFile = <span class="hljs-keyword">true</span>; <span class="hljs-comment">//移除文件标志位为真</span> <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>; } } <span class="hljs-keyword">catch</span> (IOException e) { e.printStackTrace(); <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>; } <span class="hljs-keyword">finally</span> { <span class="hljs-keyword">if</span> (in != <span class="hljs-keyword">null</span>) { <span class="hljs-keyword">try</span> { in.close(); } <span class="hljs-keyword">catch</span> (IOException e) { e.printStackTrace(); } } <span class="hljs-keyword">if</span> (removeFile) remove(key); <span class="hljs-comment">//移除缓存</span> } } </code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li></ul>
getAsString(String key)方法里首先通过缓存管理器的mCache.get(key)方法获取文件,然后用Utils.isDue(readString)**判断是否字符串数据到期,未到期返回去除时间信息的字符串内容;到期则移除缓存,返回空。**Utils.isDue(readString)调用了isDue(byte[] data)判断:
<code class="hljs java has-numbering"> <span class="hljs-javadoc">/** * 判断缓存的byte数据是否到期 * *<span class="hljs-javadoctag"> @param</span> data *<span class="hljs-javadoctag"> @return</span> true:到期了 false:还没有到期 */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">isDue</span>(<span class="hljs-keyword">byte</span>[] data) { String[] strs = getDateInfoFromDate(data); <span class="hljs-keyword">if</span> (strs != <span class="hljs-keyword">null</span> && strs.length == <span class="hljs-number">2</span>) { String saveTimeStr = strs[<span class="hljs-number">0</span>]; <span class="hljs-keyword">while</span> (saveTimeStr.startsWith(<span class="hljs-string">"0"</span>)) { saveTimeStr = saveTimeStr.substring(<span class="hljs-number">1</span>, saveTimeStr.length()); } <span class="hljs-keyword">long</span> saveTime = Long.valueOf(saveTimeStr); <span class="hljs-keyword">long</span> deleteAfter = Long.valueOf(strs[<span class="hljs-number">1</span>]); <span class="hljs-keyword">if</span> (System.currentTimeMillis() > saveTime + deleteAfter * <span class="hljs-number">1000</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>; } } <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>; } </code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li></ul>
至此整个缓存字符串读取过程在ACache的源码分析完成,其他缓存数据类型读取方法分析过程一样。
JsonObject、JsonArray、Bitmap、Drawable、序列化的存入缓存都是转化为字符串/byte格式,再调用函数put(String key, String value)即可。
比如BitMap的保存:
<code class="hljs java has-numbering"> <span class="hljs-javadoc">/** * 保存 bitmap 到 缓存中,有保存时间 * *<span class="hljs-javadoctag"> @param</span> key * 保存的key *<span class="hljs-javadoctag"> @param</span> value * 保存的 bitmap 数据 *<span class="hljs-javadoctag"> @param</span> saveTime * 保存的时间,单位:秒 */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">put</span>(String key, Bitmap value, <span class="hljs-keyword">int</span> saveTime) { put(key, Utils.Bitmap2Bytes(value), saveTime); }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li></ul>
Bitmap的读取:
<code class="hljs java has-numbering"> <span class="hljs-javadoc">/** * 读取 bitmap 数据 * *<span class="hljs-javadoctag"> @param</span> key *<span class="hljs-javadoctag"> @return</span> bitmap 数据 */</span> <span class="hljs-keyword">public</span> Bitmap <span class="hljs-title">getAsBitmap</span>(String key) { <span class="hljs-keyword">if</span> (getAsBinary(key) == <span class="hljs-keyword">null</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>; } <span class="hljs-keyword">return</span> Utils.Bytes2Bimap(getAsBinary(key)); }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>
思想就是把bitmap转化为byte[], 再调用缓存byte的函数 。通过Utils.Bitmap2Bytes(value)完成Bitmap → byte[] 的转换。通过Utils.Bytes2Bimap(getAsBinary(key))完成byte[] → Bitmap的转换。
<code class="hljs cs has-numbering"> <span class="hljs-comment">/* * Bitmap → byte[] */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">byte</span>[] <span class="hljs-title">Bitmap2Bytes</span>(Bitmap bm) { <span class="hljs-keyword">if</span> (bm == <span class="hljs-keyword">null</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>; } ByteArrayOutputStream baos = <span class="hljs-keyword">new</span> ByteArrayOutputStream();<span class="hljs-comment">//byte[]输出流</span> bm.compress(Bitmap.CompressFormat.PNG, <span class="hljs-number">100</span>, baos);<span class="hljs-comment">//按指定的图片格式以及画质,将图片转换为输出流。压缩图片,不压缩是100,表示压缩率为0 </span> <span class="hljs-keyword">return</span> baos.toByteArray(); } <span class="hljs-comment">/* * byte[] → Bitmap */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Bitmap <span class="hljs-title">Bytes2Bimap</span>(<span class="hljs-keyword">byte</span>[] b) { <span class="hljs-keyword">if</span> (b.length == <span class="hljs-number">0</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>; } <span class="hljs-keyword">return</span> BitmapFactory.decodeByteArray(b, <span class="hljs-number">0</span>, b.length);<span class="hljs-comment">//解析</span> }</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li></ul>
很简单吧。Drawable的缓存就是先转化为Bitmap,之后就是上面的步骤转换成byte。