Tomcat 使用Redis儲存Session的詳解

來源:互聯網
上載者:User

Tomcat Redis Session Github 地址。

下載 commons-pool2-2.2.jar,jedis-2.5.2.jar,tomcat-redis-session-manager-2.0.0.jar 這三個包,將其放到 tomcat 目錄下的lib目錄下。

修改tomcat 的conf目錄下的 context.xml 檔案。

在Context中插入下面的代碼。

 代碼如下 複製代碼

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
    <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
     host="localhost"
     port="6389"
     database="0"
     maxInactiveInterval="60"
     />

更詳細的方式可以查看github的配置。

這樣就配置好了一件簡單的使用redis儲存session的環境,對於叢集可以採取相同的配置。

測試Servlet:

 代碼如下 複製代碼

@WebServlet(urlPatterns = "/myhttp")
public class MyHttpServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //擷取session
        HttpSession httpSession = request.getSession;
        httpSession.setAttribute("name","name");
        //設定為0 永不到期
        httpSession.setMaxInactiveInterval(1000);
        //使httpserssion無效
//        httpSession.invalidate;
        System.out.println(httpSession.getId);
        response.getWriter.print("http");
    }
}

啟動tomcat,訪問 http://localhost:8080/myhttp則可以在redis下看到

證明環境已經配置成功,可以使用了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.