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>

       在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring session支持,而@EnableRedisHttpSession这个注解是由spring-session-data-redis提供的,所以在pom.xml文件中spring-session-data-redis

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 classRedisSessionConfig {
 
}

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

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

相关配置修改

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

spring.redis.host=192.168.1.103

所有实体类实现Serializable接口

public classSysResourceimplementsSerializable

查看效果

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

总结

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

注意事项

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

 

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

 

购买完整视频,请前往:http://www.mark-to-win.com/TeacherV2.html?id=287