2

Has anyone successfully configured two hikari connection pools with different datasources in a spring boot application? How do I do it using application.properties?

ramkris
  • 292
  • 1
  • 6
  • 15
  • 1
    Possible duplicate of https://stackoverflow.com/questions/27614301/spring-boot-multiple-datasource – Kedar Joshi Jan 08 '18 at 15:54
  • 2
    Possible duplicate of [Spring Boot Configure and Use Two DataSources](https://stackoverflow.com/questions/30337582/spring-boot-configure-and-use-two-datasources) – Todd Jan 08 '18 at 17:02

1 Answers1

3

I know that this was asked a long time ago, but I think that it might help others. In addition, I don't think that the "possible duplicates" mentioned above answer the question.

I'm using spring boot 2.0.4 with maven. Instead of having a dedicated scope for hikary, as you would if you use one db, e.g.

  datasource:
      hikari:
            connection-test-query: SELECT 1 FROM DUAL
            minimum-idle: 1
            maximum-pool-size: 2
            pool-name: some-pool-name

You can take the settings that you want and put the directly inside the db scope, e.g.:

spring:
    datasource:
        db1:
            type: com.zaxxer.hikari.HikariDataSource
            maximum-pool-size: 2
            minimum-idle: 1
            pool-name: db1-pool
            connection-test-query: SELECT 1 FROM DUAL
            jdbc-url: jdbc:mysql://${host1}:${port1}/${db1}
            username: ${db1-user}
            password: ${db1-pass}
            driver-class-name: com.mysql.cj.jdbc.Driver
        db2:
            type: com.zaxxer.hikari.HikariDataSource
            maximum-pool-size: 2
            minimum-idle: 1
            pool-name: db2-pool
            connection-test-query: SELECT 1 FROM DUAL
            jdbc-url: jdbc:mysql://${host2}:${port2}/${db2}
            username: ${db2-user}
            password: ${db2-pass}
            driver-class-name: com.mysql.cj.jdbc.Driver

As you can see the pool-name and size were set inside that scope.

Then in a java configuration file:

@Configuration
public class AppConfiguration {

....

    @Bean("db1")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource firstDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean("db2")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }
}
MosheSh
  • 31
  • 2