Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 把服務器資料快取成本地儲存的實作思路

編輯:關於 Android 程式設計

介面反覆打 API 除了吃流量,也讓伺服器壓力白白上升。把回應字串快取到本機,是最簡單也最有效的一招。這篇整理一套「侵入性低、可隨時替換」的快取方案。

挑選現成開源元件

沒必要自己從零打造,有兩個夠用的小工具:

  • Reservoir:以物件形式做快取,這裡用來存字串。
  • DiskLruCache:SD 卡上的 LRU 檔案存取工具。

設計思路

本質上就是「把介面回傳的字串存到本機」。來源不必然要是網路,任何字串都能存,甚至換成資料庫也無妨,端看需求。

幾個設計原則:

  • 在不影響既有程式碼的前提下嵌入快取邏輯,且方便日後替換實作。
  • 每個介面可以自訂快取過期時間,來源可以是伺服器回傳的 Header,也可以是本地寫死的值。
  • 載入流程:把該介面的所有請求參數 toString() 後取 MD5 當作 key,同時記錄寫入時間與有效時間;讀取時比對當前時間、寫入時間與有效時間,判斷快取是否還能用。

由於實作簡單,還有不少可以打磨的空間,例如不同介面用不同時間、快取過期後先沿用舊資料再背景更新、或完全離線模式等等。

簡化版的時間記錄

需要額外保存的資訊不多,所以用兩個 LinkedHashMap 就夠,不必動用資料庫:

private static LinkedHashMap<String, Long> cacheTimeMills;  // 寫入時間
private static LinkedHashMap<String, Long> cacheTimeValid;  // 有效時長

改造既有網路層

/** 快取檢查:若命中且未過期,直接走解析流程,不再打網路 */
protected boolean postCheck(final Context context, final boolean isShow, final String content,
                            PostUrlInfo postUrlInfo, final RequestParams params,
                            final IParser iParse, final INetCallBack callBack) {
    // 未啟用快取的介面,直接交回網路層
    if (postUrlInfo.isEnabledCache() == false) {
        return false;
    }

    // 嘗試取出快取字串,重點在 get 方法內的過期判斷
    String response = Reservoir.get(postUrlInfo.reqIndentKey, String.class);
    if (TextUtils.isEmpty(response)) {
        return false;
    }

    // 沿用原網路層的解析流程,但標記為快取來源,且不再回寫快取
    DialogFragment dialogFragment = new ProgressDialogFragment(content);
    ParseResult parseResult = new ParseResult();
    parseResult.isNetParse = false;

    parseTask task = new parseTask(dialogFragment, iParse, callBack, 0,
            getDefaultHeaders(params), response, postUrlInfo, parseResult);
    task.execute();

    // 已處理完畢,呼叫端不需再發網路請求
    return true;
}

/** 把 URL 資訊封裝起來,方便計算 key */
protected void post(final Context context, final boolean isShow, final String content,
                    String relativePath, final RequestParams params,
                    final IParser iParse, final INetCallBack callBack) {
    PostUrlInfo urlInfo = new PostUrlInfo(BaseURL, relativePath);
    post(context, isShow, content, urlInfo, params, iParse, callBack);
}

/** 擴充版:多傳一個快取時間 */
protected void post(long cacheTime, final Context context, final boolean isShow, final String content,
                    String relativePath, final RequestParams params,
                    final IParser iParse, final INetCallBack callBack) {
    PostUrlInfo urlInfo = new PostUrlInfo(BaseURL, relativePath);
    urlInfo.setDefaultCacheTime(cacheTime);
    post(context, isShow, content, urlInfo, params, iParse, callBack);
}

/** 真正的載入入口 */
protected void post(final Context context, final boolean isShow, final String content,
                    final PostUrlInfo postUrlInfo, final RequestParams params,
                    final IParser iParse, final INetCallBack callBack) {
    if (params == null) {
        return;
    }
    Logger.i(postUrlInfo.getPostUrl());
    Logger.i(params.toString());

    // 計算這次請求的 key;若有隨機數等不適合參與計算的欄位,可在 getReqIdentifiter 中排除
    postUrlInfo.reqIndentKey = getReqIdentifiter(postUrlInfo, params);

    if (postCheck(context, isShow, content, postUrlInfo, params, iParse, callBack)) {
        return;
    }

    // 網路成功後可在此回寫快取:
    // Reservoir.put(postUrlInfo.reqIndentKey, response, postUrlInfo.getDefaultCacheTime());

    client.post(context, postUrlInfo.getPostUrl(),
            (org.apache.http.Header[]) getDefaultHeaders(params),
            params, null, new AsyncHttpResponseHandler() {
                // 原有回呼邏輯
            });
}

快取內容的 AES 加解密

快取字串落在裝置上,若內容敏感,建議先加密再寫入。以下是一個可直接沿用的 AES 工具類:

package com.anupcowkur.reservoir;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EnDecrypt {

    private static final String AES  = "AES";
    private static final String MD5  = "MD5";
    private static final String UTF8 = "UTF-8";

    public static String encrypts(String sourContent, String password) {
        try {
            return parseByte2HexStr(encrypt(sourContent, password));
        } catch (Exception ex) {
            return sourContent;
        }
    }

    public static String decrypts(String cryContent, String password) {
        try {
            byte[] decryptFrom = parseHexStr2Byte(cryContent);
            return new String(decrypt(decryptFrom, password));
        } catch (Exception ex) {
            return cryContent;
        }
    }

    private static byte[] encrypt(String content, String password) throws Exception {
        SecretKeySpec key = buildKey(password);
        Cipher cipher = Cipher.getInstance(AES);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(content.getBytes(UTF8));
    }

    private static byte[] decrypt(byte[] content, String password) throws Exception {
        SecretKeySpec key = buildKey(password);
        Cipher cipher = Cipher.getInstance(AES);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(content);
    }

    private static SecretKeySpec buildKey(String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        kgen.init(128, new SecureRandom(password.getBytes(UTF8)));
        SecretKey secretKey = kgen.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), AES);
    }

    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low  = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static String md5(String s) throws Exception {
        MessageDigest m = MessageDigest.getInstance(MD5);
        m.update(s.getBytes(UTF8));
        byte[] digest = m.digest();
        return new BigInteger(1, digest).toString(16);
    }
}

安全提醒

這個 AES 實作用「密碼字串直接產生金鑰」,本質上等同於把金鑰硬編在 APK 裡,反編譯後很容易被還原。若資料真的敏感,建議改用 Android Keystore 產生並保存金鑰,讓金鑰留在硬體支援的安全區域內,永不以明文形式離開裝置。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved