美文网首页Linux成长库
nginx+tomcat+redis实现负载均衡以及sessio

nginx+tomcat+redis实现负载均衡以及sessio

作者: 泡菜爱上WaSabi | 来源:发表于2018-06-07 15:57 被阅读0次
  • 实验环境
    基于VMware虚拟机,4台虚拟机,下关配置如下表
    image.png
  • 准备session共享依赖jar包
    image.png
    依赖jar包集合下载
    链接:https://pan.baidu.com/s/1SHNxal7EbDY-pMMj0ynEsg 密码:olkk
  • 配置nginx中的nginx.conf
vim nginx.conf
http {

upstream test {  
    server 192.168.1.157:8080 max_fails=1 fail_timeout=5s;  
    server 192.168.1.156:8080 max_fails=1 fail_timeout=5s;  
}  

}

修改nginx.conf的location上下文

server {
   location / {
     root   html;  
     index  index.html index.htm;  
     proxy_pass http://test;  
  }
}
  • 在$TOMCAT_HOME/lib中添加依赖jar包

    image.png
  • 配置tomcat中的context.xml

<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.100"  
   port="6379"  
   database="0"  
   maxInactiveInterval="60" />  
</Context>  
  • 在webapps目录下新建text目录,并且再tomcat/webapps/text放一个index.jsp
[root@localhost text]# vim index.jsp 

<%@ page language="java" %>
<html>
  <head><title>TomcatA</title></head>
  <body>
  <h1 style="color: red;">TomcatA</h1>
    <table align="centre" border="1">
      <tr>
        <td>Session ID</td>
        <td><%= session.getId() %></td>
      </tr>
      <tr>
        <td>Created on</td>
        <td><%= session.getCreationTime() %></td>
     </tr>
    </table>
  </body>
</html>
sessionID:<%=session.getId()%>
<br>
SessionIP:<%=request.getServerName()%>
<br>
SessionPort:<%=request.getServerPort()%>
<%
//为了区分,第二个可以是B  
out.println("This is Tomcat Server A");
%>
  • 启动tomcat、nginx、redis,并访问 http://192.168.1.155/text/
    效果如下图:
    建议使用Chrome浏览器无痕模式,消除缓存影响,效果立马呈现

    session.gif
    可以看到虽然Server从TomcatA变为TomcatB,但session的创建时间没有变化,这就完成了session共享。
                                           THE END
    

相关文章

网友评论

    本文标题:nginx+tomcat+redis实现负载均衡以及sessio

    本文链接:https://www.haomeiwen.com/subject/rvhgjftx.html