分布式session

使用Spring Boog + Spring Session + Redis

Yml配置

server:
  port: 8089
spring:
  session:
    store-type: redis
    timeout: 3600s
    redis:
      flush-mode: on_save
      namespace: session

  redis:
    host: 127.0.0.1
    port: 6379
    timeout: 5000ms

启动类

package com.xbb.session;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@SpringBootApplication
// maxInactiveIntervalInSeconds = 60 --> Session过期时间
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 200)
public class SessionApplication {

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

}

Controller

package com.xbb.session.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @RequestMapping("/login")
    public String login(HttpServletRequest request,String username,String password){
        System.out.println("username : " + username);
        System.out.println("password : " + password);
        request.getSession().setAttribute("username",username);
        request.getSession().setAttribute("password",password);
        return "login Success";
    }

    @RequestMapping("/query")
    public String query(HttpServletRequest request){
        String username = (String) request.getSession().getAttribute("username");
        String password = (String) request.getSession().getAttribute("password");
        return username.concat("  ").concat(password);
    }
}

你可能感兴趣的:(session)