首页 > 编程语言 > 详细

通过spring session 实现session共享

时间:2020-05-07 01:29:17      阅读:50      评论:0      收藏:0      [点我收藏+]

通过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共享是在同一个域名下的多个服务间进行的。

通过spring session 实现session共享

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!