How can I do relational database-based HTTP Session Persistence in Spring 4?

前端 未结 3 2081
我在风中等你
我在风中等你 2020-12-14 12:42

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

相关标签:
3条回答
  • 2020-12-14 12:46

    Now spring boot supports by 'spring-session-jdbc'. You can save session into db with less code. For more example you can look at https://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot-jdbc.html#httpsession-jdbc-boot-sample

    0 讨论(0)
  • 2020-12-14 13:05

    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);
       }
    }
    

    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);
    }
    

    Example solution https://github.com/Mati20041/spring-session-jpa-repository

    0 讨论(0)
  • 2020-12-14 13:12

    Just slap Spring Session on it, and you're done. Adding a Redis client bean and annotating a configuration class with @EnableRedisHttpSession is all you need.

    0 讨论(0)
提交回复
热议问题