<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<jsp:forward page="HelloServlet"></jsp:forward>
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
HttpSession session= request.getSession();
int port = request.getLocalPort();
// 用户第一次访问的时候,生成随机的userId,并设置到session域中
if(session.getAttribute("userId") == null){
String userId = String.valueOf(new Random().nextInt(100)) ;
session.setAttribute("userId", userId);
response.getWriter().append("<h1>Hello, " + userId + ", this is " + port + " port</h1>");
}else{
// 用户刷新页面的时候,直接获取其userId
String userId = (String) session.getAttribute("userId");
response.getWriter().append("Welcome back, " + userId +", this is " + port +" port") ;
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
http {
upstream myserver {
# 改为windows的IP
server 10.0.0.1:8080 weight=1;
server 10.0.0.1:8081 weight=1;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
proxy_pass http://myserver;
proxy_connect_timeout 10;
}
......
}
}
/usr/local/nginx/sbin/nginx -s reload
10.0.0.101/nginx_demo
,其中IP是nginx所在服务器的IP,刷新页面可以看到轮询的将请求转发到10.0.0.1:8080和10.0.0.1:8081apply plugin: 'java'
version = '1.2'
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.apache.tomcat', name: 'tomcat-catalina', version: '7.0.99'
compile group: 'redis.clients', name: 'jedis', version: '2.10.2'
// compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
// testCompile group: 'junit', name: 'junit', version: '4.+'
}
确保依赖的版已经修改为我们改过之后的版本
jedis-2.10.2.jar
、commons-pool2-2.4.3.jar
、slf4j-api-1.7.22.jar
和tomcat-redis-session-manager-1.2-tomcat-7-1.2.jar
放到tomcat的lib目录下context.xml
配置文件,在Context
标签中添加以下内容:<!-- 注意,标签是Valve,而不是Value,类名也是RedisSessionHandlerValve而不是RedisSessionHandlerValue -->
<Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<!-- redis的IP和端口修改为你自己的 -->
<Manager className="com.radiadesign.catalina.session.RedisSessionManager" host="10.0.0.101" port="6379" database="0" maxInactiveInterval="60" />
测试成功!