共享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 就这样,是不是很简单?~~~~~~~~~~~~~~~~~~(麻蛋,我纠结了一个多小时没理解,我是菜鸡~~~~~~~~~~~)

  

最新文章

  1. maven和svn区别
  2. [Excel] WorkBook.SaveAs
  3. 查看Oracle中是否有锁表的sql
  4. Windows 部署 Redis 群集
  5. 用C#开发的双色球走势图(一)
  6. Xamarin学习资源收集
  7. nginx fastcgi php-fpm的关系梳理
  8. 刚開始学习的人制作VMOS场效应管小功放
  9. Python科学计算之Pandas
  10. Word常用实用知识3
  11. Error:Failed to load project configuration:xxxxxxxxxxxxxxxxxxxx cannot read file .idea/misc.xml
  12. Aras前端的一些知识
  13. execution(* com.sample.service.impl..*.*(..))
  14. 【洛谷P1972】HH的项链 离线+树状数组
  15. codeoforces 975B Mancala
  16. java 正则表达式(内附例子)
  17. 从咖啡馆的经营看 Web 应用的扩展
  18. 快速理解 Phoenix : SQL on HBASE
  19. JS文档DOM
  20. HDU4701_Game

热门文章

  1. 使用 LD_PRELOAD 变量拦截调用
  2. (二)初探Maven之设置代理和阿里云镜像
  3. PHP中的数组
  4. 自定义Maven Archetype模板
  5. html-webpack-plugin详解
  6. vue 中的translation操作----动态值
  7. 初识正则表达式matcher.group
  8. Python3 指定文件夹下所有文件(包括子目录下的文件)拷贝到目标文件夹下
  9. Nginx开启gzip压缩解决react打包文件过大
  10. thrift安装及python和c++版本调试