简介
示例代码点击打开链接
session共享方式
1、使用nginx反向代理做负载均衡 可以通过ip_hash方式实现一个ip访问一台服务器;有前提条件nginx要能拿到用户的真实ip
2、应用实现,如spring-session+redis
本文主要说明第二种
spring-session实现
原理通过filter将session替换为Redis处理
主要类有:
RedisHttpSessionConfiguration继承SpringHttpSessionConfiguration
SpringHttpSessionConfiguration声明SessionRepositoryFilter类型的名为springSessionRepositoryFilter的filter
SessionRepositoryFilter的doFilterInternal方法实现对request、response的封装
通过内部类SessionRepositoryRequestWrapper继承HttpServletRequestWrapper重写getSession方法
SessionRepositoryResponseWrapper
HttpServletRequestWrapper为HttpServletRequest的默认实现类
源码
@Bean
public <S extends ExpiringSession> SessionRepositoryFilter<? extends ExpiringSession> springSessionRepositoryFilter(
SessionRepository<S> sessionRepository) {
SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<S>(
sessionRepository);
sessionRepositoryFilter.setServletContext(this.servletContext);
if (this.httpSessionStrategy instanceof MultiHttpSessionStrategy) {
sessionRepositoryFilter.setHttpSessionStrategy(
(MultiHttpSessionStrategy) this.httpSessionStrategy);
}
else {
sessionRepositoryFilter.setHttpSessionStrategy(this.httpSessionStrategy);
}
return sessionRepositoryFilter;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
request.setAttribute(SESSION_REPOSITORY_ATTR, this.sessionRepository);
SessionRepositoryRequestWrapper wrappedRequest = new SessionRepositoryRequestWrapper(
request, response, this.servletContext);
SessionRepositoryResponseWrapper wrappedResponse = new SessionRepositoryResponseWrapper(
wrappedRequest, response);
HttpServletRequest strategyRequest = this.httpSessionStrategy
.wrapRequest(wrappedRequest, wrappedResponse);
HttpServletResponse strategyResponse = this.httpSessionStrategy
.wrapResponse(wrappedRequest, wrappedResponse);
try {
filterChain.doFilter(strategyRequest, strategyResponse);
}
finally {
wrappedRequest.commitSession();
}
}