All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.turbospaces.jdbc.HikariDataSourceFactoryBean Maven / Gradle / Ivy

package com.turbospaces.jdbc;

import java.util.Objects;

import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.cloud.service.ServiceInfo;
import org.springframework.cloud.service.common.PostgresqlServiceInfo;

import com.turbospaces.boot.Bootstrap;
import com.turbospaces.boot.BootstrapAware;
import com.zaxxer.hikari.HikariDataSource;

import io.micrometer.core.instrument.binder.db.PostgreSQLDatabaseMetrics;

public class HikariDataSourceFactoryBean extends AbstractFactoryBean implements BootstrapAware {
    private final Logger log = LoggerFactory.getLogger(getClass());
    private final ServiceInfo appInfo;
    private Bootstrap bootstrap;
    private JdbcPoolServiceConfig jdbcCfg;

    public HikariDataSourceFactoryBean(ServiceInfo appInfo) {
        this.appInfo = Objects.requireNonNull(appInfo);
    }
    public HikariDataSourceFactoryBean(ServiceInfo appInfo, JdbcPoolServiceConfig jdbcCfg) {
        this.appInfo = Objects.requireNonNull(appInfo);
        this.jdbcCfg = Objects.requireNonNull(jdbcCfg);
    }
    @Override
    public void setBootstrap(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
        if (Objects.isNull(jdbcCfg)) {
            jdbcCfg = new JdbcPoolServiceConfig(bootstrap.props(), false);
        }
    }
    public void setJdbcCfg(JdbcPoolServiceConfig jdbcCfg) {
        this.jdbcCfg = jdbcCfg;
    }
    @Override
    public Class getObjectType() {
        return HikariDataSource.class;
    }
    @Override
    protected HikariDataSource createInstance() throws Exception {
        DatasourceCreator creator = new DatasourceCreator(bootstrap.meterRegistry());
        HikariDataSource db = creator.create(appInfo, jdbcCfg);

        if (appInfo instanceof PostgresqlServiceInfo) {
            PostgresqlServiceInfo psi = (PostgresqlServiceInfo) appInfo;
            new PostgreSQLDatabaseMetrics(db, psi.getPath()).bindTo(bootstrap.meterRegistry());
        }

        return db;
    }
    @Override
    protected void destroyInstance(HikariDataSource instance) throws Exception {
        if (instance != null) {
            StopWatch stopWatch = StopWatch.createStarted();
            log.info("about to close JDBC pool now ...");
            instance.close();
            stopWatch.stop();
            log.info("closed JDBC pool in {}", stopWatch);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy