Many SELECT and UPDATE queries to spring_session table due to websocket

`Hello,

I’m facing an issue using a spring boot 3 application that implement a websocket communication with other angular application

In fact,I’m configuring my application to create spring session only for websocket requests and avoid creating session for other requests

the configuration is like the following:

security config class: I configured the session to be stateless

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Bean
public SecurityFilterChain configure(final HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(r -> r
.requestMatchers("/actuator/**", "/public/**", "/v2/api-docs", "/swagger-resources/**",
"/swagger-ui/**", "/swagger/**","/swagger-ui.html", "/api/user/profile",
"/stompwebsocket/**"
)
.permitAll()
.requestMatchers("/v2/registration/**").hasRole("ADMIN")
.requestMatchers("/v3/**").hasRole("ADMIN")
.anyRequest().authenticated()
).csrf(AbstractHttpConfigurer::disable)
.oauth2ResourceServer(o -> o.authenticationManagerResolver(authenticationManagerResolver))
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
</code>
<code>@Bean public SecurityFilterChain configure(final HttpSecurity http) throws Exception { http .authorizeHttpRequests(r -> r .requestMatchers("/actuator/**", "/public/**", "/v2/api-docs", "/swagger-resources/**", "/swagger-ui/**", "/swagger/**","/swagger-ui.html", "/api/user/profile", "/stompwebsocket/**" ) .permitAll() .requestMatchers("/v2/registration/**").hasRole("ADMIN") .requestMatchers("/v3/**").hasRole("ADMIN") .anyRequest().authenticated() ).csrf(AbstractHttpConfigurer::disable) .oauth2ResourceServer(o -> o.authenticationManagerResolver(authenticationManagerResolver)) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } </code>
@Bean
    public SecurityFilterChain configure(final HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(r -> r
                        .requestMatchers("/actuator/**", "/public/**", "/v2/api-docs", "/swagger-resources/**",
                                "/swagger-ui/**", "/swagger/**","/swagger-ui.html", "/api/user/profile",
                                "/stompwebsocket/**"
                        )
                        .permitAll()
                        .requestMatchers("/v2/registration/**").hasRole("ADMIN")
                        .requestMatchers("/v3/**").hasRole("ADMIN")
                        .anyRequest().authenticated()
                ).csrf(AbstractHttpConfigurer::disable)
                .oauth2ResourceServer(o -> o.authenticationManagerResolver(authenticationManagerResolver))
                .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        return http.build();
    }

Websocket config class: i added an interceptor to create session for websocket

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfigurationSession extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> {
@Override
protected void configureStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/stompwebsocket").setAllowedOrigins("*")
.addInterceptors(new HttpSessionHandshakeInterceptor());
}
}
</code>
<code>@Configuration @EnableWebSocketMessageBroker @EnableScheduling public class WebSocketConfigurationSession extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> { @Override protected void configureStompEndpoints(StompEndpointRegistry stompEndpointRegistry) { stompEndpointRegistry.addEndpoint("/stompwebsocket").setAllowedOrigins("*") .addInterceptors(new HttpSessionHandshakeInterceptor()); } } </code>
@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfigurationSession extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> {
       
        @Override
    protected void configureStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint("/stompwebsocket").setAllowedOrigins("*")
                .addInterceptors(new HttpSessionHandshakeInterceptor());
    }

}

This is the interceptor class:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor {
private static final Logger logger = LoggerFactory.getLogger(HttpSessionHandshakeInterceptor.class);
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
logger.info("Handshake interceptor called!!");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession();
attributes.put("sessionId", session.getId());
logger.info("Websocket session with id {} created", session.getId());
}
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
</code>
<code>public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor { private static final Logger logger = LoggerFactory.getLogger(HttpSessionHandshakeInterceptor.class); @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { logger.info("Handshake interceptor called!!"); if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; HttpSession session = servletRequest.getServletRequest().getSession(); attributes.put("sessionId", session.getId()); logger.info("Websocket session with id {} created", session.getId()); } return true; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { } } </code>
public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(HttpSessionHandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        logger.info("Handshake interceptor called!!");
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession();
            attributes.put("sessionId", session.getId());
            logger.info("Websocket session with id {} created", session.getId());
        }

        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}

Now , the problem is that many SELECT and UPDATE queries are triggered by spring session
and in the application log i received continiously this message:

DEBUG o.s.s.w.h.S.SESSION_LOGGER.getSession – No session found by id: Caching result for getSession(false) for this HttpServletRequest.

And also by checking the pg_stat_statements table i found that many SELECT and UPDATE calls are performed to the spring_session table:

SELECT calls, query FROM pg_stat_statements WHERE query LIKE ‘%’ || ‘SPRING_SESSION’ || ‘%’ order by calls desc;

(https://i.sstatic.net/GewEvxQE.jpg)

What should i do to fix this issue and avoid having a huge number of SELECT and UPDATE queries to spring_session table ?

Thanks in advance for you help`

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật