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<String> resourcePatterns=new ArrayList<>();
        //resourcePatterns.add("classpath*:mapper/pgsqlmapper/*.xml");
        //resourcePatterns.add("classpath*:mapper/pgsqlmapper/*/*.xml");
        //Set<Resource> 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<String> resourcePatterns=new ArrayList<>();
        //resourcePatterns.add("classpath*:mapper/mysqlmapper/*.xml");
        //resourcePatterns.add("classpath*:mapper/mysqlmapper/*/*.xml");
        //Set<Resource> 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.

Spring Boot配置HikariCP数据源非常简单。你可以按照以下步骤进行操作: 1. 首先,确保你的项目中已经引入了HikariCP的依赖。Spring Boot默认使用HikariCP作为连接池,因此你无需额外添加依赖。 2. 接下来,打开你的`application.properties`(或`application.yml`)文件,添加以下配置: ```properties # 数据源配置 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=myusername spring.datasource.password=mypassword spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # HikariCP连接池配置 spring.datasource.hikari.maximum-pool-size=10 spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.connection-timeout=30000 spring.datasource.hikari.idle-timeout=600000 ``` 如果你使用的是`application.yml`,则配置如下: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/mydatabase username: myusername password: mypassword driver-class-name: com.mysql.cj.jdbc.Driver hikari: maximum-pool-size: 10 minimum-idle: 5 connection-timeout: 30000 idle-timeout: 600000 ``` 根据你的需求进行配置参数的调整。 3. 最后,在你的应用程序中,你可以直接使用`javax.sql.DataSource`类型的`dataSource` bean来获取数据库连接,并执行相关操作。Spring Boot会自动根据配置创建对应的HikariCP数据源。 你可以在你的类中使用`@Autowired`注解将数据源自动注入: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.sql.DataSource; @SpringBootApplication public class YourApplication { @Autowired private DataSource dataSource; // ... public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 通过以上步骤,你就成功配置HikariCP数据源。希望对你有所帮助!如有任何问题,请随时提问。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值