'Shutown Spring when DB is lost

Use case

Our spring-boot-backend (v 2.3.1) using a postgres-database with HikariCP as connection pool.
The application is online and a admin accidentally kills the database.

Expected behavior

Spring notice that the connection to DB was lost. The application will gracefully shutdown.

Actual behavior

Spring is still running. All methods, which needs the db, ending up in exceptions.
To recover a complete good state, we need manually to restart spring.

Notes
We have a lot of async workers and they cannot recover correctly, when the database is going back online.
And docker/kubernetes will notice when the application shutdown and can automatically restart it.

Question

How can I reach the expected behavior?
Sadly I found nothing similar in the web.



Solution 1:[1]

If its spring 2.0, you may call the shut-down actuator from some monitoring service.

Solution 2:[2]

You can disable the actuator default provided health indicators in your property files and replace your custom DatasourceHealthIndicator by register it as bean.

@Bean
public DataSourceHealthIndicator dataSourceHealthIndicator(){
    return new DataSourceHealthIndicator(dataSource, "SELECT 1");
}
@Component
@RequiredArgsConstructor
public class CustomHealth implements HealthIndicator {

    @Override
    public Health health() {
        ...
        return Health.status(healthIndicator.health().getStatus()).build();
    }

    private final DataSourceHealthIndicator healthIndicator;
}
YML

management:
  health:
    db:
      enabled: false
      
Properties

management.health.db.enabled: false

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zubair
Solution 2 Lunatic