zoukankan      html  css  js  c++  java
  • 展开被 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 就这样,是不是很简单?~~~~~~~~~~~~~~~~~~(麻蛋,我纠结了一个多小时没理解,我是菜鸡~~~~~~~~~~~)

       

  • 相关阅读:
    ural1238. Folding(记忆化)
    URAL1410. Crack
    树套树Day1线段树套平衡树bzoj3196
    noipd2t3列队
    NOIP2017D1T3
    uoj279温暖会指引我们前行
    一篇打脸文
    Link-Cut Tree
    重口味费用流
    bzoj1000~1025
  • 原文地址:https://www.cnblogs.com/xjbBill/p/10120845.html
Copyright © 2011-2022 走看看