在Spring 4中如何进行基于关系数据库的HTTP会话持久性? [英] How can I do relational database-based HTTP Session Persistence in Spring 4?
问题描述
我需要能够将HTTP会话存储在关系数据库中,以便跨多个前端服务器对前端用户进行无状态负载平衡.如何在Spring 4中实现这一目标?
I need to be able to store the HTTP Session in a relational database in order to do stateless load balancing of my front-end users across multiple front-end servers. How can I achieve this in Spring 4?
我知道如何使用Redis做到这一点,但是似乎没有关于如何使用关系数据库做到这一点的文档. Postgres.
I see how one can do this with Redis, however there does not appear to be documentation on how to do this with a relational database e.g. Postgres.
推荐答案
使用Spring Session(它会透明地覆盖Java EE中的HttpSession),您只需采用SessionRepository
接口并使用自定义ex即可实现. JdbcSessionRepository
.这很容易做到.实现后,只需手动添加(不需要@EnableRedisHttpSession
批注)创建的过滤器即可过滤链,例如波纹管:
With Spring Session (it transparently will override HttpSessions from Java EE) you can just take SessionRepository
interface and implement it with your custom ex. JdbcSessionRepository
. It is kind of easy to do. When you have your implementation, then just add manually (you don't need @EnableRedisHttpSession
annotation) created filter to filter chain, like bellow:
@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
).
Here you have how SessionRepository
interface looks like. It has only 4 methods to implement. For how to create Session object, you can look in MapSessionRepository
and MapSession
implementation (or RedisOperationsSessionRepository
and 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 4中如何进行基于关系数据库的HTTP会话持久性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!