緩存能顯著提升數據訪問速度、降低數據庫壓力。以商城首頁商品列表為例:數據公共、變動低、訪問頻高,極適合緩存。無緩存時每請求必查 DB;有緩存後,首次查 DB 存入緩存,後續直接讀緩存返回。
數據存於用戶 Session,隔離性好,但無法跨用戶共享,適合用戶個性化數據。
代碼示例:緩存遊戲列表 5 分鐘,過期自動失效。
HttpSession session = request.getSession();
if (session.getAttribute("allGamesDataList") != null) {
returnJsonObject = (JSONObject) session.getAttribute("allGamesDataList");
response.getWriter().println(returnJsonObject.toString());
return;
}
// ... 查詢數據庫 ...
session.setMaxInactiveInterval(5 * 60);
session.setAttribute("allGamesDataList", returnJsonObject);
解決 Session 無法跨頁/跨用戶共享的問題。典型場景:用戶 Token 緩存,避免每次驗證查 DB。
單例類:
public class ShareSingleton {
public JSONObject UsrTokenDictionary;
private static ShareSingleton instance;
private ShareSingleton() { UsrTokenDictionary = new JSONObject(); }
public static ShareSingleton getInstance() {
if (instance == null) instance = new ShareSingleton();
return instance;
}
public void VerifyTokenForInterface(String RequestToken) { /* ... */ }
}
寫入 Token:String ecryptToKenUUID = UUID.randomUUID().toString(); // ... 更新數據庫 ... ShareSingleton.getInstance().UsrTokenDictionary.put(LoginId, ecryptToKenUUID);
將非敏感、小體積數據存瀏覽器,減輕服務端壓力,但受大小(4KB)與安全性限制。
| 方案 | 作用域 | 適用場景 | 注意點 |
|---|---|---|---|
| Session | 用戶會話 | 用戶私有、時效性數據 | 集群需同步,內存壓力大 |
| 單例 | 全局應用 | 全局共享、只讀為主、熱點數據 | 線程安全、內存洩漏、重啟丟失 |
| Cookie | 客戶端 | 偏好設定、追蹤標識 | 不可信、大小受限、每請求攜帶 |
生產環境建議引入 Redis、EhCache 等專業緩存中間件,解決分布式、持久化、淘汰策略等進階需求。