前言
Nginx+Tomcat对Session的管理一直有了解,但是一直没有实际操作一遍,本文从最简单的安装启动开始,通过实例的方式循序渐进的介绍了几种管理session的方式。
nginx安装配置
1.安装nginx
[root@localhost ~]# yum install nginx
提示报如下错误:
No package nginx available.
解决办法安装epel:EPEL是企业版 Linux 附加软件包的简称,EPEL是一个由Fedora特别兴趣小组创建、维护并管理的,针对 红帽企业版 Linux(RHEL)及其衍生发行版(比如 CentOS、Scientific Linux、Oracle Enterprise Linux)的一个高质量附加软件包项目;
[root@localhost ~]# yum install epel-release
安装完之后,即可成功安装nginx;
2.启动、停止nginx
先进入nginx的目录
[root@localhost nginx]# cd /usr/sbin/
执行命令
./nginx 开启 ./nginx -s stop 使用kill命令强制杀掉进程 ./nginx -s quit 待nginx进程处理任务完毕进行停止 ./nginx -s reload
nginx+tomcat负载均衡
1.准备2个tomcat,分别指定端口为8081,8082
drwxr-xr-x. 9 root root 4096 May 7 14:16 apache-tomcat-7.0.88_8081 drwxr-xr-x. 9 root root 4096 May 7 14:16 apache-tomcat-7.0.88_8082
修改webapps/ROOT的index.jsp,方便测试
<%
if(request.getSession().getAttribute("key")==null){
out.println("key is null,ready init.....");
request.getSession().setAttribute("key","value");
}else{
out.println("key is not null,key="+request.getSession().getAttribute("key"));
}
%>
<br>
sessionID:<%=session.getId()%>
<br>
sessionCreateTime:<%= session.getCreationTime() %>
<br>
<%
out.println("tomcat port 8081");
%>
最后的输出在两个tomcat下面指定各自的端口号8081和8082
2.nginx配置负载均衡(默认策略)
修改/etc/nginx/下面的nginx.conf
upstream tomcatTest {
server 127.0.0.1:8081; #tomcat-8081
server 127.0.0.1:8082; #tomcat-8082
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://tomcatTest;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
此处配置的负载均衡策略是默认的轮询策略,nginx还支持其他策略包括:ip_hash、weight、fair(第三方)、url_hash(第三方);
默认策略每个web请求按时间顺序逐一分配到不同的后端服务器,这种情况下每次请求都会创建一个新的session,下面做简单测试:









