基于nginx+redis+tomcat 实现session 共享

1、安装好多个tomcat,并安装好redis,在apache-tomcat-7.0.75\lib 目录下添加如下这三个包

image.png

2、修改apache-tomcat-7.0.75\conf\context.xml  

<?xml version='1.0' encoding='utf-8'?>

<!--

  Licensed to the Apache Software Foundation (ASF) under one or more

  contributor license agreements.  See the NOTICE file distributed with

  this work for additional information regarding copyright ownership.

  The ASF licenses this file to You under the Apache License, Version 2.0

  (the "License"); you may not use this file except in compliance with

  the License.  You may obtain a copy of the License at


      http://www.apache.org/licenses/LICENSE-2.0


  Unless required by applicable law or agreed to in writing, software

  distributed under the License is distributed on an "AS IS" BASIS,

  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  See the License for the specific language governing permissions and

  limitations under the License.

-->

<!-- The contents of this file will be loaded for each web application -->

<Context>


    <!-- Default set of monitored resources -->

    <WatchedResource>WEB-INF/web.xml</WatchedResource>


    <!-- Uncomment this to disable session persistence across Tomcat restarts -->

    <!--

    <Manager pathname="" />

    -->


    <!-- Uncomment this to enable Comet connection tacking (provides events

         on session expiration as well as webapp lifecycle) -->

    <!--

    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />

    -->

    <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />

        <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"

         host="192.168.1.111" 

         port="6379" 

         database="0" 

         maxInactiveInterval="60" />


</Context>


其中192.168.1.111为自己的redis 服务器IP


3、在apache-tomcat-7.0.75_02\webapps\ROOT 下写一个测试界面index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

<%

String username =  request.getParameter("username");

if(username!=null){

request.getSession().setAttribute("username", username);

}

%>

</head>

<body>

<form action="index.jsp" method="post">

<input type="text" name="username">

<input type="submit" value="提交">

</form>

您现在访问的是9999服务器,用户名为:${username}


</body>

</html>

注:9999为该台tomcat服务器端,测试时不同服务器修改成不一样的


4、安装好nginx 修改nginx.conf 加入如下配置


image.png

server 配置多个

image.png


5、先启动redis,再启动tomcat,最后启动nginx,在浏览器中访问http://localhost/

image.png


此时输入admin 点提交,多次涮新,可以看到不管跳到8080,还是9999,服务器的session 都可以获取到

image.png


image.png




猜你喜欢

转载自blog.51cto.com/4923168/2285042