How to make app still run when the hikaridatasource bean cannot be created due to some external datasource problem?

Viewed 94

when there will be an issue with the external database for a live webapp and bean won't be able to get instantiated when retried again by the application then app goes down how can we fix this problem?

@Bean(destroyMethod = "close")
public DataSource dataSource(){
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName("com.mysql.jdbc.Driver");
    hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/spring-test"); 
    hikariConfig.setUsername("root");
    hikariConfig.setPassword("admin");

    hikariConfig.setMaximumPoolSize(5);
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setPoolName("springHikariCP");

    hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

    HikariDataSource dataSource = new HikariDataSource(hikariConfig);

    return dataSource;
}
1 Answers

Your code will probably throw an exception if the datasource is down. Wrap it into try/catch like so:

try {
   <your code goes here>
} catch (Exception e) {
   return null;
}

But code calling for a datasource will have to accept the result may be null rather than throwing NullPointerExceptions.

Related