高併發訪問時如何確保伺服器端session過多而造成記憶體溢位致使伺服器宕機的方法之一
使用者登入後所在登入頁面中設定一個隱藏的iframe標籤。該子頁面會每隔10s中向報告一次線上訊息。程式碼如下:
……
<divclass="response">
<iframesrc="response.html"></iframe>
</div>
……
response.html程式碼實現如下:
<!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<metahttp-equiv="pragma"content="no-cache"></meta>
<metahttp-equiv="Cache-Control"content="no-cache, must-revalidate"></meta>
<metahttp-equiv="expires"content="0"></meta>
<metahttp-equiv="content-type"content="text/html;
charset=utf-8"></meta>
<scripttype="text/javascript"src="js/ajax.js"></script>
<scripttype="text/javascript">
window.onload = function() {
setInterval(response, 10000);
}
function response() {
var url ="response"
ajaxGet(url);
}
</script>
</head>
<body></body>
</html>
伺服器端程式每接受一次請求,在未退出的情況下將該會話的生存時間延長
package web.execute;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import web.standard.PlainServlet;
publicclass ResponseServletextends PlainServlet {
privatestaticfinallongserialVersionUID = 6549090l;
@Override
publicvoid service(HttpServletRequest request, HttpServletResponse response)throws IOException {
super.service(request, response);
HttpSession session = request.getSession(false);
if (session ==null || session.getAttribute("userId") == null) {
return;
}
if (System.currentTimeMillis() - session.getLastAccessedTime() < 10) {
return;
}
session.setMaxInactiveInterval(15);
System.out.println("responseServlet...");
}
}