zoukankan      html  css  js  c++  java
  • (38)Spring Boot分布式Session状态保存Redis【从零开始学Spring Boot】

    【本文章是否对你有用以及是否有好的建议,请留言】

    在使用spring boot做负载均衡的时候,多个app之间的session要保持一致,这样负载到不同的app时候,在一个app登录之后,而访问到另外一台服务器的时候,session丢失。

           常规的解决方案都是使用:如apache使用mod_jk.conf,使用Memcached进行共享。

           在开发spring boot app的时候可以借助 spring session redis或者ehcache,用外置的redis或者ehcache来存储session的状态,这里使用redis进行介绍,ehcache实现是一样的。

    增加相关依赖

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

     

     

    RedisSessionConfig.java

    package com.wisely.base;
     
    import org.springframework.context.annotation.Configuration;
    import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
     
    @Configuration
    @EnableRedisHttpSession
    public class RedisSessionConfig {
     
    }

     

    如果需要添加失效时间可以使用以下的写法:

    @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60) //1分钟失效

    相关配置修改

    application.properties修改redis配置信息(请自行安装redis),请根据实际修改。如:

    spring.redis.host=127.0.0.1

     

    所有实体类实现Serializable接口

    public class UserInfo implements Serializable

     

    查看效果

    这时候登录系统在不同的app之间跳转的时候,session都是一致了,redis上可以看到:

    总结

    使用这些代码之后 ,无论你使用nginx或者apache,都无须在关心多个app之间的session一致的问题了。

     

    注意事项

    1redis版本号需要是2.8以上否则会抛异常:ERR Unsupported CONFIG parameter: notify-keyspace-events

     

    2RedisSessionConfig需要放在App.java启动类可以扫描的位置;

     

    【Spring Boot 系列博客】

     

    0)前言【从零开始学Spring Boot :

    http://412887952-qq-com.iteye.com/blog/2291496

     

    1spring boot起步之Hello World【从零开始学Spring Boot:

    http://412887952-qq-com.iteye.com/blog/2291500

    2Spring Boot返回json数据【从零开始学Spring Boot

    http://412887952-qq-com.iteye.com/blog/2291508

    (15)Spring Boot使用Druid和监控配置【从零开始学Spring Boot】

    http://412887952-qq-com.iteye.com/blog/2292362

    16Spring Boot使用Druid(编程注入)【从零开始学Spring Boot

    http://412887952-qq-com.iteye.com/blogs/2292376

    17Spring Boot普通类调用bean【从零开始学Spring Boot】:

    http://412887952-qq-com.iteye.com/blog/2292388

    ......

    (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    http://412887952-qq-com.iteye.com/blog/2294942

     

     

    更多查看博客:http://412887952-qq-com.iteye.com/

     

  • 相关阅读:
    2013第49周四开发一定要细心
    2013第49周三IE9文档模式
    2013第49周二要转变
    2013第49周一jsp标签
    2013第48周11月工作小结
    2013第48周六记
    2013第48周五开发日记
    BZOJ 1269 文本编辑器 Splay
    审批流程设计方案-介绍(一)
    Web挖掘技术
  • 原文地址:https://www.cnblogs.com/hehehaha/p/6147104.html
Copyright © 2011-2022 走看看