Spring Boot Session共享2种方式

xiaoxiao2021-02-27  168

本文转载自:http://blog.csdn.net/shuiluobu/article/details/77418896

spring Boot(21)分布式Session:为了使Web能适应大规模的访问,需要实现应用程序的集群部署 实现集群部署首先要解决session的统一,即需要实现session的共享机制,即分布式Session。

分布式Session的实现方式

基于resin/tomcat web容器本身的session复制机制 基于NFS共享文件系统 基于Cookie进行session共享 基于数据库的Session共享 基于分布式缓存的Session共享,如memcached,Redis,jbosscache 基于ZooKeeper的Session共享

下面代码将演示基于Spring Session的实现,这个是基于redis缓存的Session共享。

方案1

如果配置的Redis的是自己在维护,那很方便就可以实现了。

Spring Session官方文档

http://docs.spring.io/spring-session/docs/current/reference/HTML5/guides/boot.html

添加依赖

只需要在pom文件添加以下依赖

org.springframework.boot

spring-boot-starter-redis

org.springframework.session

spring-session

启动类添加@EnableRedisHttpSession注解

配置文件application.properties

spring.redis.host=localhost

spring.redis.port=6379

server.session.timeout=36000

Spring Boot会自动把session从文件存储方式切换到Redis方式,根本不需要再做任何配置。

方案2

如果配置的Redis的不是自己在维护,不能够更改它的配置(如应用程序部署在阿里云,同时使用阿里云的Redis数据库),那就有点麻烦了。

额外功能

因为方案1需要Redis的一个功能:

notify-keyspace-events

默认情况下,这个功能是不开启的。

开启额外功能

如果你要使用方案1,你就必须通过下面的命令,来让你的Reids开启这个功能。

redis-cli config set notify-keyspace-events Egx

那就必须新建如下RedisSessionConfig类,即可在不改变Redis配置的前提下使用Redis来存储Session了。

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 RedisSessionConfig   package com.jege.spring.boot.Config;   import org.springframework.context.annotation.Bean;   import org.springframework.context.annotation.Configuration;   import org.springframework.session.data.redis.config.ConfigureRedisAction;   import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;   /**   * @author JE哥   * @email 1272434821@qq.com   * @description:可在不改变Redis配置的前提下使用Redis来存储Session了   */   @Configuration   //在这里设置Session过期时间,单位:秒   @EnableRedisHttpSession (maxInactiveIntervalInSeconds = 36000 )   public class RedisSessionConfig {   @Bean   public static ConfigureRedisAction configureRedisAction() {   return ConfigureRedisAction.NO_OP;   }   }

Spring Session默认会话时间

Spring Session默认的Session过期时间是30分钟。

采用方案1的时候,你可以在application.properties里配置

server.session.timeout=36000

来设置Session过期时间(单位是秒)。

如果采用方案2来配置Session,

那么application.properties里设置的Session过期时间是不起作用的。

必须使用上面RedisSessionConfig类里注解的参数来设置。

验证

需要使用nginx,配置2个tomcat来验证,需要等待。

其他关联项目

Spring Boot 菜鸟教程1-HelloWorld

http://blog.csdn.NET/je_ge/article/details/53270821

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。

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

最新回复(0)