原文地址:http://blog.csdn.net/caiwenfeng_for_23/article/details/45666831
PS:截止到2015-05-12前是不支援Tomcat8的,詳情見官網:https://github.com/jcoleman/tomcat-redis-session-manager
前提:你已經部署了Redis,尚未學會的,可以移步這裡:http://blog.csdn.net/caiwenfeng_for_23/article/details/45511007
我的案例下載:http://download.csdn.net/detail/caiwenfeng_for_23/8689847
其實很簡單,就幾個步驟:
1.配置Tomcat的conf目錄下的context.xml檔案:
1> 單點Reids配置
<!-- Jedis save session --> <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" host="localhost" port="6379" database="0" maxInactiveInterval="60"/>
1 2 3 4 5 6 7 8 9
2> Sentinel叢集配置:
<!-- Sentinel 配置 --> <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" maxInactiveInterval="60" sentinelMaster="mymaster" sentinels="127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381,127.0.0.1:26382" />
1 2 3 4 5 6 7
2.添加jar
3.測試
1>
儲存Session:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("hello"); //取得Session對象 HttpSession session=request.getSession(); //設定Session屬性 for(int i=0;i<100000;i++){ session.setAttribute("name"+i, "Magci_"+i); } }
1 2 3 4 5 6 7 8 9
2>重啟Tomcat:假如Session儲存在tomcat下,重啟後Session不存在;如果儲存在Redis下,Tomcat重啟對Session無影響
3>取出Session:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("hello"); //取得Session對象 HttpSession session=request.getSession(); //取出Session屬性 for(int i=0;i<100000;i++){ System.out.println(session.getAttribute("name"+i)); } }
1 2 3 4 5 6 7 8 9
注意事項:從Tomcat6開始預設開啟了Session持久化設定,測試時可以關閉本地Session持久化,其實也很簡單,在Tomcat的conf目錄下的context.xml檔案中,取消注釋下面那段配置即可:
<!-- Uncomment this to disable session persistence across Tomcat restarts --> <!-- <Manager pathname="" />
-->