public class ControllerServlet extends HttpServlet {
private DataSource testDS;
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Context ctx = new InitialContext();
testDS = (DataSource) ctx.lookup("jdbc/testDS"); // JNDI 查找一次,緩存供後續重用
} catch (NamingException e) { throw new ServletException(e); }
}
public DataSource getTestDS() { return testDS; }
}
避免每請求 JNDI 查找,大幅降低延遲。
server.xml <Context reloadable="false"> 或容器管理介面停用。| 策略 | 做法 | 效益 |
|---|---|---|
| 不需 Session 的頁面 | <%@ page session="false" %> | 避免建立 Session 物件 |
| 不存大型物件圖 | 只存 ID/關鍵資料,大物件放快取/資料庫 | 減少序列化開銷,提升吞吐 |
| 用畢即銷毀 | session.invalidate() | 釋放記憶體 |
| 縮短逾時 | web.xml <session-timeout>10</session-timeout> | 降低併發 Session 數量 |
maxActive/maxIdle/maxWait。SELECT *、批次處理。pageBuffer 調大 (如 32KB) 減少 flush 次數。「開發期優化代碼結構 (init 緩存、Session 精簡)、部署期優化配置 (關閉重載、預編譯、靜態分離)、運行期優化資源池 (連線、執行緒、快取)——三階段構建高效能 J2EE 應用。」