How to use HikariCP in Spring Boot with two datasources in conjunction with Flyway

后端 未结 2 882
陌清茗
陌清茗 2021-02-03 23:50

I want to use HikariCP as JDBC connection pool in my Spring boot application. I have two datasources (MySQL database as the primary database and accessing those data through Hib

相关标签:
2条回答
  • 2021-02-04 00:33

    Declaring your own DataSource will already have implicity disabled Spring Boot's auto-configuration of a data source. In other words this won't be having any effect:

    @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
    

    I think the problem lies in the fact that you aren't binding Hikari-specific configuration to your MySQL DataSource. You need to do something like this:

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.hikari")
    public DataSource mySQLDataSource() {
        return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
    }
    

    This will mean that your mySQLDataSourceProperties are configured with general-purpose data source configuration. They then create a HikariDataSource which is further configured with the Hikari-specific configuration.

    0 讨论(0)
  • 2021-02-04 00:48

    Thank you Andy for your fast and valuable answer ! You set me on the right track. After fiddling around, I found this configuration is working for me :

        @Bean
        @Primary
        @ConfigurationProperties("spring.datasource") 
      //@ConfigurationProperties("spring.datasource.hikari") can also be used, no difference
        public DataSourceProperties mySQLDataSourceProperties() {
            return new DataSourceProperties();
        }
    
        @Bean
        @Primary
        @ConfigurationProperties("spring.datasource.hikari")
        public DataSource mySQLDataSource() {
            return mySQLDataSourceProperties().initializeDataSourceBuilder().build();
        }
    
        @Bean
        @ConfigurationProperties(prefix = "spring.datasource.hikari")
        public HikariConfig hikariConfig() {
            return new HikariConfig();
        }
    
        @Bean
        public DataSource dataSource() {
            return new HikariDataSource(hikariConfig());
        }
    

    and I had to add these settings in the application.properties:

    # this is absolutely mandatory otherwise BeanInstantiationException in mySQLDataSource ! 
    spring.datasource.url=${JDBC_CONNECTION_STRING}
    
    spring.datasource.hikari.jdbc-url=${JDBC_CONNECTION_STRING}
    
    spring.datasource.hikari.username=user
    spring.datasource.hikari.password=pass
    
    0 讨论(0)
提交回复
热议问题