| 策略 | 優點 | 缺點 |
|---|---|---|
| 數據緩存 | 內存佔用小、靈活 | 需業務層改造、模板渲染仍消耗 CPU |
| 內容緩存(頁面片段) | 實現簡單、直接緩存 HTML 輸出 | 難以個性化、緩存失效控制複雜 |
本文方案:內容緩存 + EL 表達式動態注入,兼顧效能與個性化。
<jc:cache id="fragmentId" scope="application">...</jc:cache> 包裹頁面片段。applicationScope 變數。${...})不求值。ExpressionEvaluator API 動態計算 EL 表達式值並替換,實現「靜態骨架 + 動態數據」。public static Object eval(String expr, Class<?> type, JspContext ctx) throws JspException {
if (expr.indexOf("${") == -1) return expr; // 無表達式直接返回
ExpressionEvaluator evaluator = ctx.getExpressionEvaluator();
return evaluator.evaluate(expr, type, ctx.getVariableResolver(), null);
}
<tag>
<name>cache</name>
<tag-class>com.devsphere.articles.jspcache.CacheTag</tag-class>
<body-content>scriptless</body-content>
<attribute><name>id</name><required>true</required></attribute>
<attribute><name>scope</name><required>false</required></attribute>
</tag>
<tag>
<name>dynamic</name>
<tag-class>com.devsphere.articles.jspcache.DynamicTag</tag-class>
<body-content>empty</body-content>
<attribute><name>expr</name><required>true</required></attribute>
</tag>
SimpleTagSupport,doTag() 中判斷緩存是否存在。getJspBody().invoke(fragmentWriter) 輸出,存入 applicationScope[id]。<jc:dynamic expr="..."/> 標記,調用 JspUtils.eval() 計算替換,最終輸出。<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="jc" uri="https://devsphere.com/articles/jspcache" %>
<c:if test="${empty sessionScope.counter}">
<c:set var="counter" value="0" scope="session"/>
</c:if>
<c:set var="counter" value="${counter+1}" scope="session"/>
<jc:cache id="cachedFragmentWithCounter" scope="application">
<p>您是第 <jc:dynamic expr="${sessionScope.counter}"/> 次訪問此片段。</p>
<p>當前時間:${pageContext.request.locale}(靜態緩存部分)</p>
</jc:cache>
效果:HTML 骨架緩存,計數器每請求動態更新。
<context-param>
<param-name>cacheEnabled</param-name>
<param-value>true</param-value>
</context-param>
生產環境可通過此參數一鍵關閉緩存,便於調試。
applicationScope Map,支援 LRU、TTL、大小限制、統計監控。<c:import> 實現頁面組件化緩存(Edge Side Includes ESI 思想)。