在使用Spring Cloud框架的時候,Http的請求首先會到達Spring Cloud Gateway服務,並與之建立session對象,但是在默認情況下,請求結果之後,session會立刻過期。有些業務場景可能會在session中存儲一些數據,比如登陸狀態,如果登陸之後,長時間沒有訪問,再次訪問的時候,讓用戶重新登陸等,都需要控制session的空閒時間。在Spring Cloud Gateway中,默認管理session的類是InMemoryWebSessionStore
,它裏面的內部類InMemoryWebSession
實現了WebSession
接口。在這個接口,有兩個方法,有來設置和獲取session的最大空閒時間:
@Override
public void setMaxIdleTime(Duration maxIdleTime) {
this.maxIdleTime = maxIdleTime;
}
@Override
public Duration getMaxIdleTime() {
return this.maxIdleTime;
}
所以,要想修改它的空閒最大時間,就需要調用setMaxIdleTime方法進行設置。
另外,session過期檢測的方法如下:
@Override
public boolean isExpired() {
return isExpired(clock.instant());
}
private boolean isExpired(Instant now) {
if (this.state.get().equals(State.EXPIRED)) {
return true;
}
if (checkExpired(now)) {
this.state.set(State.EXPIRED);
return true;
}
return false;
}
private boolean checkExpired(Instant currentTime) {
return isStarted() && !this.maxIdleTime.isNegative() &&
currentTime.minus(this.maxIdleTime).isAfter(this.lastAccessTime);
}
在這個代碼裏面有一個isStarted
方法,在裏面會判斷,如果設置了session是start狀態,或者session裏面有屬性值時,isStarted
才返回true。
遺憾的是,session的最大空閒值默認是不能在application.yml中直接配置的,如果想修改最大空閒,可以添加過濾器實現,如下所示:
import java.time.Duration;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.server.WebSession;
@Service
public class SessionGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
WebSession session = exchange.getSession().block();
session.setMaxIdleTime(Duration.ofDays(7));
return chain.filter(exchange);
};
}
}
然後在application.yml中添加下面的配置,讓過濾器生效:
spring:
cloud:
gateway:
discovery:
locator:
enabled: true
default-filters:
- Session
這樣就成功修改了session的最大空閒時間了。一般session中存儲了一些數據時,才需要設置最大空閒參數。