通过spring session 实现session共享

通过spring session 实现session共享

通过spring session,结合redis,可以把session信息存储在redis中,实现多个服务间的session共享。

以下介绍在springboot工程中如何使用spring session

一、引入依赖

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、在配置类中开启对RedisHttpSession的支持

在配置类加注解@EnableRedisHttpSession

二、 在配置文件中对redis进行配置

server:
  port: 8080
spring:
  redis:
    host: localhost
    port: 6379
    jedis:
      pool:
        max-idle: 10
        max-active: 8
        max-wait: -1
        min-idle: 0

接下来对session的使用和未使用spring session前一致。


@RestController
public class LogInController {

    @GetMapping("/login")
    public String login(@RequestParam("username") String username, HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.setAttribute("username",username);
        return username+",login success";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        Object username = session.getAttribute("username");
        session.invalidate();
        return username+",logout success";
    }

    @GetMapping("/index")
    public String sayHello(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        System.out.println(session);
        if(session==null){
            return "未登录";
        }
        Object username = session.getAttribute("username");
        return username+",welcome";
    }
}

将当前工程复制一份,改变端口为8082,在工程一中访问/login进行登录,启动工程2,在工程2中访问/index可以获取到登录信息,两个服务间实现了session共享。

注意这里的session共享是在同一个域名下的多个服务间进行的。

原文地址:https://www.cnblogs.com/chengxuxiaoyuan/p/12839713.html