如何在 Spring 4 中执行基于关系数据库的 HTTP 会话持久性? [英] How can I do relational database-based HTTP Session Persistence in Spring 4?

查看:16
本文介绍了如何在 Spring 4 中执行基于关系数据库的 HTTP 会话持久性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够将 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 做到这一点,但是似乎没有关于如何用关系数据库做到这一点的文档,例如邮政.

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 中的 HttpSessions),您只需采用 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 对象,你可以查看 MapSessionRepositoryMapSession 实现(或 RedisOperationsSessionRepositoryRedisSession).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆