spring boot 共享session redis实现

xiaoxiao2021-02-28  102

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

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

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

增加相关依赖

1 2 3 4 5 6 7 8 9 < 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

1 2 3 4 5 6 7 8 9 10 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一致的问题了。

注意事项

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

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

转载请注明原文地址: https://www.6miu.com/read-65145.html

最新回复(0)