AJAX模式的興起徹底改變了Web交互范式:從「用戶填表→提交→跳轉」的同步請求響應,轉向「豐富客戶端持續異步交互」。這帶來極佳用戶體驗的同時,也給服務端擴展性帶來嚴峻挑戰——典型AJAX應用的併發連接數是傳統Web的3-4倍,每個HTTP請求佔用一個執行線程,頻繁的輪詢請求極易耗盡線程池。
WebLogic自6.1版本起提供weblogic.servlet.FutureResponseServlet,支持真正的異步服務端推送,無需客戶端輪詢、無需服務端佔用持久執行線程。核心機制:
flush()。public class AsynchronousServerResponseServlet extends FutureResponseServlet {
private final Notifier notifier;
public AsynchronousServerResponseServlet() {
this.notifier = new Notifier();
this.notifier.start(); // 啟動單一異步處理線程
}
public void service(HttpServletRequest request, FutureServletResponse response)
throws IOException, ServletException {
// 將客戶端請求推入緩衝區,立即返回,不佔用執行線程
notifier.poll(request, response);
}
class Notifier extends Thread {
private static Stack<Client> clients = new Stack<>();
void poll(HttpServletRequest request, FutureServletResponse response) {
clients.push(new Client(request, response));
}
public void run() {
while (!clients.empty()) {
Client client = null;
try {
client = clients.pop();
PrintWriter pw = client.response.getWriter();
for (int j = 0; j < 10; j++) {
pw.println("Time is: " + new Date() + "<br>");
pw.flush(); // 關鍵:立即推送到客戶端
}
pw.close();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try { client.response.send(); } catch (IOException ioe) { ioe.printStackTrace(); }
}
}
}
}
class Client {
private HttpServletRequest request;
private FutureServletResponse response;
private Client(HttpServletRequest request, FutureServletResponse response) {
this.request = request;
this.response = response;
}
}
}
Notifier線程循環處理所有客戶端,避免「一連接一線程」模式的線程爆炸。PrintWriter並分批flush(),最終調用send()提交響應。Notifier僅負責分發;引入心跳機制檢測死連接;集成消息隊列(Kafka/RocketMQ)解耦事件產生與推送。Servlet 3.0引入request.startAsync()標準化異步處理,現代容器(Tomcat 7+、Jetty 8+、WebLogic 12c+)均支持。新項目優先採用標準API,避免廠商鎖定;維護WebLogic舊系統時,FutureResponseServlet仍是可靠選擇。
異步Servlet模式是高併發實時Web應用的基石,掌握其「線程解耦、連接複用、事件驅動」核心思想,比具體API更具價值。