zoukankan      html  css  js  c++  java
  • springboot 使用redis 实现session共享

    说明:在工程项目需求很大的情况下,部署项目的时候可能会使用分布式部署或者集群,这样的跨服务器使用的时候,session就会出现丢失,这个时候可以使用redis共享session

    一:导包

    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
        </parent>
        <dependencies>
            <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>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
        </dependencies>

    二:配置redis 信息

    spring.redis.host=127.0.0.1
    spring.redis.port=6379

    三:配置启动类

    @SpringBootApplication
    @EnableRedisHttpSession(maxInactiveIntervalInSeconds= 1800) //spring在多长时间后强制使redis中的session失效,默认是1800.(单位/秒)
    public class DemoApplication {

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

    四:写controller进行测试

    //测试redis
    @GetMapping("/testRedis")
    public AjaxResult test1(HttpSession session) throws Exception{
    //RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),(String) SecurityUtils.getSubject().getSession().getId());
    //RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),String.valueOf(session.getId()));

    session.setAttribute("admin","haha");
    String haha = (String) session.getAttribute("admin");
    return new AjaxResult(session.getId()+"----"+haha);
    }

    @GetMapping("/getRedis")
    public AjaxResult test2(HttpSession session) throws Exception{
    //RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),(String) SecurityUtils.getSubject().getSession().getId());
    //RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),String.valueOf(session.getId()));
    String haha = (String) session.getAttribute("admin");
    return new AjaxResult(haha);
    }

    这样的话,session就保存到到了redis中,可查看key值为spring:session:sessions进行查看.

    退出后,redis中的session失效.

    如不自动退出,到了"过程3"中配置的@EnableRedisHttpSession(maxInactiveIntervalInSeconds= 3600) 时间后,redis中的session也会自动失效.

    在这个过程中出现的坑:jar包版本冲突,最主要的是,我使用的版本和springboot的版本一致竟然都不行,然后我就使用的最新的版本:

    <dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>2.1.3.RELEASE</version>
    </dependency>

  • 相关阅读:
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    综合练习:词频统计
    Hadoop综合大作业
    理解MapReduce
    熟悉常用的Hbase操作
    熟悉的HDFS操作
    爬取晨星网对各公司主要职位的分析
  • 原文地址:https://www.cnblogs.com/haoxiu1004/p/10374533.html
Copyright © 2011-2022 走看看