在分布式系统中,如果想要集中存储会话状态,一般会用到redis来存储会话,但是使用spring-session-data-redis时,会把所有请求都去访问redis,包括静态资源文件,解决方法是加一个过滤器判断,从而绕过session filter
如:所有以/static/开头的url,都绕过session filter,从而不去访问session
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.session.web.http.SessionRepositoryFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Order(SessionRepositoryFilter.DEFAULT_ORDER - 1)
public class ExcludeUrlFilter extends OncePerRequestFilter {
/**
* 多个url以逗号分割 例如:/static/js,/css/
*/
@Value("${spring.session.exclude.url}")
private String url;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
boolean flag = excludeUrl(request.getRequestURI(), url);
if(flag) {
request.setAttribute("org.springframework.session.web.http.SessionRepositoryFilter.FILTERED", Boolean.TRUE);
}
filterChain.doFilter(request, response);
}
private boolean excludeUrl(String requestURI, String url) {
String[] uri = url.split(",");
for(String str:uri){
if(requestURI.startsWith(str)){
return true;
}
}
return false;
}
}