前提:你已經部署了Redis,還沒有學會的,能夠移步這裏:http://blog.csdn.net/caiwenfeng_for_23/article/details/45511007 java
個人案例下載:http://download.csdn.net/detail/caiwenfeng_for_23/8689847 git
其實很簡單,就幾個步驟:
1.配置Tomcat的conf目錄下的context.xml文件: github
<!-- 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"/>
2> Sentinel集羣配置: redis
<!-- 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" />
3.測試 tomcat
1>
存儲Session: 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); } }
2>重啓Tomcat:假如Session保存在tomcat下,重啓後Session不存在;若是保存在Redis下,Tomcat重啓對Session無影響 測試
3>取出Session: this
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)); } }
注意事項:從Tomcat6開始默認開啓了Session持久化設置,測試時能夠關閉本地Session持久化,其實也很簡單,在Tomcat的conf目錄下的context.xml文件中,取消註釋下面那段配置便可: spa
<!-- Uncomment this to disable session persistence across Tomcat restarts --> <!-- <Manager pathname="" /> -->
能夠嘗試運行上面的demo案例! .net