Springboot not clearing Hikari Pool when refreshing datasource

I am trying to update my datasource with dynamic credentials that I get via Hashicorp Vault. I followed this tutorial: https://developer.hashicorp.com/vault/tutorials/app-integration/spring-reload-secrets This works very well and reliably so far. However, I have the problem that every time I update the secrets, spring does not shut down the current hikari pool and instead open another one on top. So the current connections remain in MariaDB, which of course leads to the following message from MariaDb after a certain time: Too many connections. Even closing the datasources before the context.refresh doesn’t help.

application.properties:

# configure access to Vault
spring.cloud.vault.uri=https://xxx.xxx
spring.cloud.vault.token=0000-0000-0000

# set up configuration import from Vault
spring.config.import=vault://

# configure KV backend
spring.cloud.vault.kv.enabled=false

# configure database secrets engine
spring.cloud.vault.database.enabled=true
spring.cloud.vault.database.role=db-role
spring.cloud.vault.database.backend=database

# tune lease renewal and expiry threshold for 8 minute max ttl
spring.cloud.vault.config.lifecycle.min-renewal=120s
spring.cloud.vault.config.lifecycle.expiry-threshold=40s

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://xxx.xxx.xxx.xxxx:3306/

DatasourceConfig:

@Configuration
@Slf4j
public class DatasourceConfig {

    @Bean
    @RefreshScope
    public DataSource meeteryDataSource(DataSourceProperties properties) {

        String base = "base";

        String meetery_db_drv = properties.getDriverClassName();
        String meetery_db_url = properties.getUrl();
        String meetery_db_usr = properties.getUsername();
        String meetery_db_pwd = properties.getPassword();

        Map<Object, Object> resolvedDataSources = new HashMap<>();
        List<String> tenants = getAllTenants(db_drv, db_url, db_usr, db_pwd, base);

        for(String tenant : tenants) {
            DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();

            dataSourceBuilder.driverClassName(meetery_db_drv);

            dataSourceBuilder.url(db_url.replace("_base", "_" + tenant));
            dataSourceBuilder.username(db_usr);
            dataSourceBuilder.password(db_pwd);
            resolvedDataSources.put(tenant, dataSourceBuilder.build());

        }

        AbstractRoutingDataSource dataSource = new MeeteryMultiTenantDatasource();
        dataSource.setDefaultTargetDataSource(resolvedDataSources.get(base));
        dataSource.setTargetDataSources(resolvedDataSources);

        dataSource.afterPropertiesSet();
        return dataSource;

    }

    private List<String> getAllTenants(String db_drv, String db_url, String db_usr, String db_pwd, String base) {
        List<String> tenants = new ArrayList<>();

        DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName(meetery_db_drv);
        dataSourceBuilder.url(meetery_db_url);
        dataSourceBuilder.username(meetery_db_usr);
        dataSourceBuilder.password(meetery_db_pwd);
        DataSource dataSource = dataSourceBuilder.build();

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT meeting_uuid from tbl_01_meeting");

        tenants.add(base);

        for (Map<String, Object> row : rows) {
            tenants.add((String) row.get("meeting_uuid"));
        }

        return tenants;
    }
}

VaultRefresher:

VaultRefresher(@Value("${spring.cloud.vault.database.role}") String databaseRole,
                   @Value("${spring.cloud.vault.database.backend}") String databaseBackend,
                   SecretLeaseContainer leaseContainer,
                   ContextRefresher contextRefresher)
    {

        String vaultCredsPath = String.format("%s/creds/%s", databaseBackend, databaseRole);

        log.info("Vault credentials path: {}", vaultCredsPath);

        leaseContainer.addLeaseListener(event -> {
            if (vaultCredsPath.equals(event.getSource().getPath())) {
                if (event instanceof SecretLeaseExpiredEvent) {
                    MeeteryapiApplication.shutdownHikariPool();
                    contextRefresher.refresh();
                    log.info("Refresh database credentials");
                }
            }
        });
    }

MeeteryMultiTenantDatasource:

public class MeeteryMultiTenantDatasource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return MeeteryTenantContext.getCurrentTenant();
    }
}

MeeteryapiApplication:

@SpringBootApplication
@EnableMethodSecurity(proxyTargetClass = true, securedEnabled = true, jsr250Enabled = true)
public class MeeteryapiApplication {

    private static ConfigurableApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(MeeteryapiApplication.class, args);
    }

    public static void shutdownHikariPool() {
        if (applicationContext != null) {
            MeeteryMultiTenantDatasource meeteryMultiTenantDatasource = applicationContext.getBean(MeeteryMultiTenantDatasource.class);
            for(Map.Entry<Object, DataSource> entry : meeteryMultiTenantDatasource.getResolvedDataSources().entrySet()) {
                DataSource ds = entry.getValue();
                if (ds instanceof com.zaxxer.hikari.HikariDataSource) {
                    ((com.zaxxer.hikari.HikariDataSource) ds).close();
                }
            }

        }

    }

}

I am really stuck at that point.

New contributor

EichD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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