首页新闻招聘找找看知识库
  • 浏览:7 2020-05-20 18:07 来自 cn2020

    spring-session-data-redis
    #####localhost:8080/session
    #####localhost:8080/get
    ###########################

     

     


    1、pom.xml
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
      </dependency>

    2、application.properties

    spring.redis.host=localhost
    spring.rabbitmq.port=6379
    spring.session.store-type=redis


    3、SpringApplication
      @EnableCaching
      @SpringBootApplication
      @EnableRedisHttpSession
      public class TestApplication {

      public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
        }

      }

    4、Controller

      @RestController
      @RequestMapping(value="/")
      public class IndexController {

        @ResponseBody
        @RequestMapping(value = "/session")
        public Map<String,Object> getSession(HttpServletRequest request){
          request.getSession().setAttribute("username","admin");
          String userName=(String)request.getSession().getAttribute("username");
          System.out.println("userName:"+userName);
          Map<String,Object> map=new HashMap<String,Object>();
          map.put("sessionId",request.getSession().getId());
          return map;
        }

        @ResponseBody
        @RequestMapping(value = "/get")
        public String get(HttpServletRequest request){
          String userName=(String)request.getSession().getAttribute("username");
          return userName;
        }
      }

登录后才能评论,请先登录注册