Tomcat7+Redis儲存Session

來源:互聯網
上載者:User

原文地址: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="" />

-->

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.