redis保存session信息
本文实现一个将session信息保存在 redis中,多个tomcat中的工程都从redis获取session信息的示例。
1、新建一个maven web 工程名为 session-redis 如下:
目录结构如下:
2、修改配置文件内容
pom.xml 中依赖如下:
UTF-8 1.7 1.7 5.0.4.RELEASE junit junit 4.11 test org.springframework spring-context ${spring.version} org.springframework spring-core ${spring.version} org.springframework spring-webmvc ${spring.version} org.springframework spring-beans ${spring.version} org.springframework spring-context-support ${spring.version} com.fasterxml.jackson.core jackson-databind 2.9.5 commons-collections commons-collections 3.2.2 ch.qos.logback logback-classic 1.2.3 org.logback-extensions logback-ext-spring 0.1.5 org.slf4j jcl-over-slf4j 1.7.25 redis.clients jedis 2.9.0 javax.servlet servlet-api 2.5 compile javax.servlet.jsp jsp-api 2.2 org.springframework.session spring-session-data-redis 2.0.4.RELEASE
web.xml 配置文件内容
Archetype Created Web Application springSessionRepositoryFilter org.springframework.web.filter.DelegatingFilterProxy springSessionRepositoryFilter /* springMvc org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath*:mvc-demo.xml 1 springMvc /
mvc-demo.xml 增加配置内容、
3、增加IndexController类,里边两个方法
index 方法返回字符串 index ,并且在session中添加属性 name 为 zhangsan ,打印sessionid
getName 方法 返回session中的name属性 .打印sessionid
如下:
@RestControllerpublic class IndexController { @GetMapping ("/index") public String index(HttpServletRequest request){ request.getSession().setAttribute("name","zhagnsan"); System.out.println("-----index------------sessionid"+request.getSession().getId()); return "index"; } @GetMapping ("/getName") public String getName(HttpServletRequest request){ System.out.println("----getName-------------sessionid======"+request.getSession().getId()); return (String)request.getSession().getAttribute("name"); }}
4、在本机启动redis服务
5、idea中配置两个tomcat 端口不能相同 我们这里 tomcat8.5-1 使用 80端口 tomcat8.5-1使用8080 端口 如下:
两个tomcat 都部署session_redis 工程如下 ,访问路径为 /
6、启动两个tomcat 访问 tomcat1 中的项目 http://localhost:80/index 在session中设置了name =zhangsan
后台打印sessionid为:
直接访问 tomcat2 中的 getName 方法 http://localhost:8080/getName 可以直接访问到 session 并且后台输出sessionid和tomcat1中相同 。所以 session保存成功。
由 于我们在配置文件中设置 session过期时间为 60秒 所以60秒后再次访问 getName方法,发现访问不到内容了如下:
7、通过redis 客户端 我们可以看到 随着session信息的保存以及过期 redis中键值的变化 ,如下:
代码下载地址: https://github.com/zhangxinmin/session-redis.git