在这个分布式的时代,Session的管理是一件比较麻烦的事情,以前我们可以设置Tomcat的Session传播达到共享,可是这样的话速度不够及时,Spring推出了Spring Session来统一管理Session,这里我们演示由redis来储存。
一、首先我们要引入依赖,修改pom.xml添加:
//引入spring session <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> </dependency> //引入redis <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
二、修改application.properties或者yml文件:
spring.redis.port=6379
spring.redis.host=127.0.0.1
spring.redis.password=密码没用可以不填
spring.redis.pool.max-active=100
spring.redis.pool.max-idle=5
spring.redis.pool.max-wait=60000
三、启用redis管理Session
//第一种方式:修改application.properties,添加
spring.session.store-type=redis
//第二种方式:启用注解
@EnableRedisHttpSession
四、进行一些简单的设置
1.使用配置文件方式修改命名空间:spring.session.redis.namespace=your_namesapce(自己起个名字)
2.使用注解修改命名空间:@EnableRedisHttpSession(redisNamespace="")
3.使用注解修改过期时间:@EnableRedisHttpSession(maxInactiveIntervalInSeconds=2000
) 单位是秒
4.bean配置
@Bean public CookieHttpSessionStrategy cookieHttpSessionStrategy(){ CookieHttpSessionStrategy cookieStrategy=new CookieHttpSessionStrategy(); DefaultCookieSerializer cookieSerializer=new DefaultCookieSerializer(); cookieSerializer.setCookieName("NAME"); cookieSerializer.setCookieMaxAge(1800); cookieStrategy.setCookieSerializer(cookieSerializer); return cookieStrategy; }