展开被 SpringBoot 玩的日子 《 四 》 Session 会话共享
共享Session-spring-session-data-redis
分布式系统中,sessiong共享有很多的解决方案,其中托管到缓存中应该是最常用的方案之一。
Spring Session官方说明
Spring Session provides an API and implementations for managing a user’s session information.
如何使用
1、引入依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
2、Session配置:
/**
* 共享 Session
* maxInactiveIntervalInSeconds = (秒)
*/
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60 * 30)
public class SessionConfig {
}
maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Boot的server.session.timeout属性不再生效
好了,这样就配置好了,我们来测试一下
3、测试
/**
* 第一次进入时,已保存(有效时长是 session 设置的maxInactiveIntervalInSeconds 时间)
* @param request
* @return
*/
@RequestMapping(value = "/first", method = RequestMethod.GET)
public Map<String, Object> firstResp (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
request.getSession().setAttribute("request Url", request.getRequestURL());
map.put("request Url", request.getRequestURL());
map.put("sessionId", request.getSession().getId());
return map;
} /**
* 获取sessionId
* @param request
* @return
*/
@RequestMapping(value = "/sessions", method = RequestMethod.GET)
public Object sessions (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
map.put("sessionId", request.getSession().getId());
map.put("message", request.getSession().getAttribute("map"));
return map;
}
这里,可能就会有人问了,怎么测验两个项目的sessionId是都相同:咋们先打一个 jar 去测试,端口是8080的,然后再把本地的项目跑起来,端口改成9090的,两个项目都跑起来之后,随便哪个项目(端口)先访问 /first ,这个接口,然后两个项目再访问一遍 /sessions 这个接口,看看sessionId 是不是相同的,不就成了?如下:
共享 session 就这样,是不是很简单?~~~~~~~~~~~~~~~~~~(麻蛋,我纠结了一个多小时没理解,我是菜鸡~~~~~~~~~~~)
最新文章
- maven和svn区别
- [Excel] WorkBook.SaveAs
- 查看Oracle中是否有锁表的sql
- Windows 部署 Redis 群集
- 用C#开发的双色球走势图(一)
- Xamarin学习资源收集
- nginx fastcgi php-fpm的关系梳理
- 刚開始学习的人制作VMOS场效应管小功放
- Python科学计算之Pandas
- Word常用实用知识3
- Error:Failed to load project configuration:xxxxxxxxxxxxxxxxxxxx cannot read file .idea/misc.xml
- Aras前端的一些知识
- execution(* com.sample.service.impl..*.*(..))
- 【洛谷P1972】HH的项链 离线+树状数组
- codeoforces 975B Mancala
- java 正则表达式(内附例子)
- 从咖啡馆的经营看 Web 应用的扩展
- 快速理解 Phoenix : SQL on HBASE
- JS文档DOM
- HDU4701_Game