SpringBoot 配置多数据源 HikariCP 连接池

1.配置.properties/.yml文件(需要注意jdbcUrl而不是url)

spring:
  datasource:
    #第一数据源
    pgsql:
      driverClassName: org.postgresql.Driver
      jdbcUrl: jdbc:postgresql://192.168.1.23:5432/databasepgsql?useUnicode=true&characterEncoding=utf8
      type: com.zaxxer.hikari.HikariDataSource
      username: postgres
      password: postgres
      initialSize: 10
      maxActive: 2000
      minIdle: 1
      maximumPoolSize: 200
      autoCommit: true
      poolName: HikariPool_pgsql
      maxLifetime: 1800000
      connectionTestQuery: SELECT 1
    #第二数据源
    mysql:
      driverClassName: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://127.0.0.1:3306/databasemysql?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&autoReconnect=true
      type: com.zaxxer.hikari.HikariDataSource
      username: root
      password: 123456
      initialSize: 10
      maxActive: 2000
      minIdle: 1
      maximumPoolSize: 200
      autoCommit: true
      poolName: HikariPool_mysql
      maxLifetime: 1800000
      connectionTestQuery: SELECT 1

2.写javaconfig 配置类,配置Hikari连接多数据源

2.1配置pgsql

@Configuration
//这里设置扫描dao接口了,启动类与dao接口就不用在配置mapper扫描注解
@MapperScan(basePackages = "com.aaa.bbb.dao.pgsqlsource", sqlSessionFactoryRef = "pgSqlSessionFactory")
public class HikariPgSqlConfig {

    /**
     * @ConfigurationProperties 读取yml中的配置参数映射成为一个对象
     */
    @Bean(name = "pgSqlDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.pgsql")
    public HikariDataSource pgSqlDateSource() {
        return new HikariDataSource();
    }

   
    @Bean(name = "pgSqlSessionFactory")
    @Primary
    public SqlSessionFactory chSqlSessionFactory(@Qualifier("pgSqlDataSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        //-----多路径是扫描
        //配置xml扫描路径
        //List resourcePatterns=new ArrayList<>();
        //resourcePatterns.add("classpath*:mapper/pgsqlmapper/*.xml");
        //resourcePatterns.add("classpath*:mapper/pgsqlmapper/*/*.xml");
        //Set resources=new LinkedHashSet<>(resourcePatterns.size());
        //for (String resourcePattern : resourcePatterns) {
        //    Resource[] resource = new PathMatchingResourcePatternResolver().getResources(resourcePattern);
        //    resources.addAll(Arrays.asList(resource));
        //}
        //Resource[] resourcesArr=new Resource[resources.size()];
        //mybatis扫描xml所在位置
        //bean.setMapperLocations(resources.toArray(resourcesArr));

        //-----单路径是扫描
        //mybatis扫描xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/pgsqlmapper/*/*.xml"));
        return bean.getObject();
    }

    @Bean("pgSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate chSqlSessionTemplate(@Qualifier("pgSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    //不配值这个bean,@Transaction注解可能失效
    //使用时 @Transactional(value = "pgSqlTransactionManager",rollbackFor = {Exception.class, RuntimeException.class})
    @Bean("pgSqlTransactionManager")
    public TransactionManager mysqlTransactionManager(){
        return new JdbcTransactionManager(pgSqlDateSource());
    }
}

2.2配置mysql

@Configuration
//这里设置扫描dao接口了,启动类与dao接口就不用在配置mapper扫描注解
@MapperScan(basePackages = "com.aaa.bbb.dao.mysqlsource", sqlSessionFactoryRef = "mySqlSessionFactory")
public class HikariMySqlConfig {

    /**
     * @ConfigurationProperties 读取yml中的配置参数映射成为一个对象
     */
    @Bean(name = "mySqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public HikariDataSource mySqlDateSource() {
        return new HikariDataSource();
    }

    @Bean(name = "mySqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mySqlDataSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        //-----多路径是扫描
        //配置xml扫描路径
        //List resourcePatterns=new ArrayList<>();
        //resourcePatterns.add("classpath*:mapper/mysqlmapper/*.xml");
        //resourcePatterns.add("classpath*:mapper/mysqlmapper/*/*.xml");
        //Set resources=new LinkedHashSet<>(resourcePatterns.size());
        //for (String resourcePattern : resourcePatterns) {
        //    Resource[] resource = new PathMatchingResourcePatternResolver().getResources(resourcePattern);
        //    resources.addAll(Arrays.asList(resource));
        //}
        //Resource[] resourcesArr=new Resource[resources.size()];
        //mybatis扫描xml所在位置
        //bean.setMapperLocations(resources.toArray(resourcesArr));

        //-----单路径是扫描
        //mybatis扫描xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/mysqlmapper/*.xml"));
        return bean.getObject();
    }

    @Bean("mySqlSessionTemplate")
    public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("mySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    //不配值这个bean,@Transaction注解可能失效
    //使用时 @Transactional(value = "mySqlTransactionManager",rollbackFor = {Exception.class, RuntimeException.class})
    @Bean("mySqlTransactionManager")
    public TransactionManager mysqlTransactionManager(){
        return new JdbcTransactionManager(mySqlDateSource());
    }
}

完成以上配置,启动程序尝试调用使用连接数据库的接口,如下打印连接池名称表示配置成功!

yyyy-MM-dd HH:mm:ss [http-nio-8081-exec-n] INFO  com.zaxxer.hikari.HikariDataSource : HikariPool_pgsql - Starting...
yyyy-MM-dd HH:mm:ss [http-nio-8081-exec-n] INFO  com.zaxxer.hikari.HikariDataSource : HikariPool_pgsql - Start completed.
yyyy-MM-dd HH:mm:ss [http-nio-8081-exec-n] INFO  com.zaxxer.hikari.HikariDataSource : HikariPool_mysql - Starting...
yyyy-MM-dd HH:mm:ss [http-nio-8081-exec-n] INFO  com.zaxxer.hikari.HikariDataSource : HikariPool_mysql - Start completed.

你可能感兴趣的:(SpringBoot,相关,数据库,相关,spring,boot,mysql,HikariPool,HikariCP)