簡體   English   中英

Spring Boot中jdbcTemplate連接泄漏到PostgreSQL數據庫

[英]jdbcTemplate connection leak to postgresql db in Spring Boot

看來我的服務有數據庫連接泄漏。 昨天重新部署后,我提到到postgres數據庫有27個打開的連接。 今天早上他們60歲。

對我的數據庫執行此查詢,我發現某些連接的上次使用時間僅為昨天。

SELECT * FROM pg_stat_activity
ORDER BY state_change DESC

在此處輸入圖片說明

看來我的jdbcTemplate應該關閉它們,但它沒有這樣做。

這是我的配置

@Configuration
public class DatabaseConfiguration {
    // reading data from application properties
    // ........

    private DataSource configureDataSource(String url, String user, String password, String driverClassName){
        DataSource ds = DataSourceBuilder.create()
                .url(url)
                .username(user)
                .password(password)
                .driverClassName(driverClassName)
                .build();

        org.apache.tomcat.jdbc.pool.DataSource configuredDataSource = (org.apache.tomcat.jdbc.pool.DataSource) ds;
        configuredDataSource.setTestWhileIdle(connectionTestWhileIdle);
        configuredDataSource.setValidationQuery( connectionValidationQuery);
        configuredDataSource.setTimeBetweenEvictionRunsMillis( 
              toIntExact(connectionTimeBetweenEvictionRunsMillis));

        return configuredDataSource;
    }

    @Bean(name = "qaDataSource")
    public JdbcTemplate getQaJdbcTemplate()  {
        DataSource ds = configureDataSource(qaURL, qaUsername, qaPassword ,qaDriverClassName);
        return new JdbcTemplate(ds);
    }

任何想法我的配置有什么問題嗎? 也許這是錯誤的數據庫配置。

經過數小時的調查,看來此連接泄漏是由http請求超時以及群集內的其他網絡問題引起的。

如果從我的服務請求到postgres數據庫的請求被發送並且發生了某些網絡問題,則連接保持活動狀態。 一段時間后,達到最大活動連接數,服務無法再連接到數據庫。

作為一種解決方法,雖然未發現網絡問題的根源,但是為了避免一段時間后服務中斷,我在configureDataSource方法中配置了RemoveAbandoned驗證

configuredDataSource.getPoolProperties().setRemoveAbandonedTimeout(300);
configuredDataSource.getPoolProperties().setRemoveAbandoned(true);

這將檢查處於活動狀態的連接不超過5分鍾,如果確實存在,則將連接視為已放棄並被關閉。 不要忘記確保RemoveAbandonedTimeout應該RemoveAbandonedTimeout服務中所有sql查詢的最長執行時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM