How to configure custom database connection timeout in Spring Boot application?

27,178

Solution 1

There are at least 3 time-outs to configure:

  1. Transaction timeouts, which you already did. I declared mine in the transactionManager bean:
txManager.setDefaultTimeout(myDefaultValue);
  1. Query timeouts(which obviously does not need @transactional), which you already did and also explained here

  2. Network timeouts(Read this excellent article).

For my case, i am using Oracle, and my bean configuration is as follows:

    @Bean
    public HikariDataSource dataSource() {
        
        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(springDatasourceDriverClassName);
        ds.setJdbcUrl(springDatasourceUrl);
        ds.setUsername(springDatasourceUsername);
        ds.setPassword(springDatasourcePassword);
        ds.setDataSourceProperties(oracleProperties());
        
        return ds;
    }
    
    Properties oracleProperties() {
        Properties properties = new Properties();
        
        properties.put("oracle.net.CONNECT_TIMEOUT", 10000);
        properties.put("oracle.net.READ_TIMEOUT", 10000);
        properties.put("oracle.jdbc.ReadTimeout", 10000);

        return properties;
    }

And if you do not want to configure a bean for the DataSource(which is what most people will do), you can configure the network timeout properties in application.properties:

spring.datasource.hikari.data-source-properties.oracle.net.CONNECT_TIMEOUT=10000
spring.datasource.hikari.data-source-properties.oracle.net.READ_TIMEOUT=10000
spring.datasource.hikari.data-source-properties.oracle.jdbc.ReadTimeout=10000

Solution 2

Depending on your datasource, but you can try this:

spring.datasource.hikari.max-lifetime=1000
spring.datasource.hikari.connection-timeout=1000
spring.datasource.hikari.validation-timeout=1000
spring.datasource.hikari.maximum-pool-size=10
Share:
27,178
yordanoff
Author by

yordanoff

Updated on April 27, 2021

Comments