打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
redis实现分布式集群环境session共享(代码示例与验证)

1、redis实现分布式集群环境session共享的好处

可以实现多机器部署同一套服务(代码),性能更好,可承受更高的用户并发

2、如何使用

1)思路是利用cookie保存sessionId

2)   配置过程

  • 在pom文件添加依赖
  1. <dependency>
  2. <groupId>org.springframework.session</groupId>
  3. <artifactId>spring-session-data-redis</artifactId>
  4. </dependency>
  • 在配置文件中开启redis session 缓存@EnableRedisHttpSession,并指定缓存的时间maxInactiveIntervalInSeconds

  • 编写测试代码
  1. @RestController
  2. public class SessionController {
  3. @RequestMapping(value = "/setSession", method = RequestMethod.GET)
  4. public Map<String, Object> setSession (HttpServletRequest request){
  5. Map<String, Object> map = new HashMap<>();
  6. request.getSession().setAttribute("request Url", request.getRequestURL());
  7. map.put("request Url", request.getRequestURL());
  8. return map;
  9. }
  10. @RequestMapping(value = "/getSession", method = RequestMethod.GET)
  11. public Object getSession (HttpServletRequest request){
  12. Map<String, Object> map = new HashMap<>();
  13. map.put("sessionIdUrl",request.getSession().getAttribute("request Url"));
  14. map.put("sessionId", request.getSession().getId());
  15. return map;
  16. }
  17. }

3、测试

由于我们是利用cookie来存储sessionid,所以我们可以在谷歌浏览器中打开隐身模式清空cookie来验证缓存的时间

1)首先我们要启动redis服务(如果是Windows用户,可参考我的命令,其中主要启动命令是redis-server.exe redis.windows.conf)

2)连接redis(可参考我的命令)

3)在隐身窗口中分别输入localhost:8080/setSession;输入localhost:8080/getSession获得sessionid

4)在redis中输入命令keys *   

5)输入ttl (并复制带expires的sessionid上图中箭头处)

可看到过期时间

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
springboot集成springsession利用redis来实现session共享
OAuth2、CAS单点登录
SpringSession
分布式Session解决方案
Javaweb重要知识点总结(三)Cookie 和 Session
request.getSession()、request.getSession(true)和request.getSession(false)的区别
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服