引入JAR
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
配置session 啟動以及配置超時
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.PostConstruct;
import java.time.Duration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig extends RedisHttpSessionConfiguration {
@Value("${server.servlet.session.timeout}")
private String timeout;
@PostConstruct
public void redisSessionConfig() {
//Duration類型時間轉成秒
long seconds = Duration.parse(timeout).getSeconds();
this.setMaxInactiveIntervalInSeconds((int) seconds);
}
}
注:
@EnableRedisHttpSession 配置redis-session生效
我配置的會話的timeout采用Duration格式的時間,也可以直接配置秒數字,自己處理就行。
springboot session配置:
spring:
session:
store-type: redis
redis:
host: localhost
port: 6379
timeout: 1000
jedis:
pool:
max-active: 100
max-wait: 10
max-idle: 10
min-idle: 10
database: 0
springboot-server.servlet.session.cookie以及超時時間配置
server:
port: 8080
servlet:
context-path: /projectname
session:
timeout: PT30M
cookie:
http-only: false
path: /
注:server.servlet.session.timeout=PT30M 是springboot2+ 配置內存session管理的超時設置,redis配置這個沿用了此配置,放在哪里都可以,自己取用時候注意下就行。
如果多項目公用session,且項目名不一樣的情況,注意配置cookie的path,session的作用范圍好像是這個。
