springboot多数据源配置
datasource:
db1:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://192.168.14.4:3306/double_prevention?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
username: root
password: root
type: com.zaxxer.hikari.HikariDataSource
db2:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://192.168.14.4:3306/wh_cloud?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=true&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC
username: root
password: root
type: com.zaxxer.hikari.HikariDataSource
package com.dp.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* @Author LLF
* @Date Created in 2022/12/23 17:56
* @Description
* @Version 2.0
**/
@Configuration
public class DataSourceConfig {
@Bean("db1DataSource")
@Qualifier("db1DataSource")
@ConfigurationProperties(prefix ="spring.datasource.db1")
public DataSource db1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean("db2DataSource")
@Qualifier("db2DataSource")
@ConfigurationProperties(prefix ="spring.datasource.db2")
public DataSource db2DataSource() {
return DataSourceBuilder.create().build();
}
}
package com.dp.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
/**
* @Author LLF
* @Date Created in 2022/12/23 18:50
* @Description
* @Version 2.0
**/
@Configuration
public class JdbcTemplateConfig {
@Bean("db1JdbcTemplate")
@Qualifier("db1JdbcTemplate")
@Primary
public JdbcTemplate db1JdbcTemplate(@Qualifier("db1DataSource") DataSource dataSource){
return new JdbcTemplate(dataSource);
}
@Bean("db2JdbcTemplate")
@Qualifier("db2JdbcTemplate")
public JdbcTemplate db2JdbcTemplate(@Qualifier("db2DataSource") DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
@Autowired @Qualifier("db1JdbcTemplate") private JdbcTemplate jdbcTemplate; @Autowired @Qualifier("db2JdbcTemplate") private JdbcTemplate jdbcTemplate2;