在這個分布式的時代,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; }