線上人數的統計(從tomcat拿到sessions的個數)
二話不說直接上程式碼:
import org.apache.catalina.Context;
import org.apache.catalina.Manager;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
程式碼:
int activeSessions = 0;
if (request instanceof RequestFacade) {
Field requestField = request.getClass().getDeclaredField("request");
requestField.setAccessible(true);
Request req = (Request) requestField.get(request);
Context context = req.getContext();
Manager manager = context.getManager();
activeSessions = manager.getActiveSessions();
}
編譯時引用了tomcat/lib下的catalina.jar,打成war包之後記得從war包中刪除catalina.jar
這時候maven的好處就來了,scope寫個provided(容器已提供)就OK了。
原理:
tomcat對request(javax.servlet.http.HttpServletRequest)的實現是org.apache.catalina.connector.RequestFacade
RequestFacade有一個protected的request (org.apache.catalina.connector.Request)屬性
request 能拿到Context (org.apache.catalina.Context)
context能拿到Manager(org.apache.catalina.Manager,tomcat管理session的類)
然後通過Manager拿到所有存活的session數,就是線上人數了。