我需要能够将 HTTP session 存储在关系数据库中,以便跨多个前端服务器对前端用户进行无状态负载平衡。如何在 Spring 4 中实现这一目标?
我看到如何使用 Redis 做到这一点,但是似乎没有关于如何使用关系数据库做到这一点的文档,例如 postman 。
最佳答案
使用 Spring Session(它会透明地覆盖 Java EE 中的 HttpSessions),您只需使用 SessionRepository
接口(interface)并使用您的自定义前实现它。 JdbcSessionRepository
.这很容易做到。完成后,只需手动添加(您不需要 @EnableRedisHttpSession
注释)创建的过滤器到过滤器链,如下所示:
@Configuration
@EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
//other stuff...
@Autowired
private SessionRepository<ExpiringSession> sessionRepository;
private HttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy(); // or HeaderHttpSessionStrategy
@Bean
public SessionRepository<ExpiringSession> sessionRepository() {
return new JdbcSessionRepository();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter<>(sessionRepository);
sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy);
http
.addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class);
}
}
在这里你有如何
SessionRepository
界面看起来。它只有 4 种方法可以实现。关于如何创建 Session 对象,您可以查看 MapSessionRepository
和 MapSession
实现(或 RedisOperationsSessionRepository
和 RedisSession
)。public interface SessionRepository<S extends Session> {
S createSession();
void save(S session);
S getSession(String id);
void delete(String id);
}
示例解决方案 https://github.com/Mati20041/spring-session-jpa-repository
关于spring - 如何在 Spring 4 中进行基于关系数据库的 HTTP session 持久性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31396362/