(38)Spring Boot分布式Session状态保存Redis【从零开始学Spring Boot】

来源:互联网 发布:命运知乎 编辑:程序博客网 时间:2024/05/21 06:40

在使用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启动类可以扫描的位置;

 

 

1 0
原创粉丝点击