Springboot mysql 多数据源

  1. application 文件配置如下:
# 数据库1
spring.datasource.jdbc-url=jdbc:mysql://192.168.0.132:3306/dbname?user=userName&password=pwd&useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.username=userName
spring.datasource.password=pwd
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

# 数据库2
weixin.spring.datasource.jdbc-url = jdbc:mysql://192.168.0.133:3306/dbname2?user= userName2&password= pwd2&useUnicode=true&characterEncoding=UTF-8&useSSL=true
weixin.spring.datasource.username = userName2
weixin.spring.datasource.password = pwd2
weixin.spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
  1. 创建 DataSourceConfig

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 org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
/**
 * @description: DataSourceConfig
 * @author: chang
 * @create: 2019-08-26 13:30
 **/
@Configuration
public class DataSourceConfig {

    // 默认使用这个数据库
    @Primary
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource primaryDataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "jobDataSource")
    @Qualifier("jobDataSource")
    @ConfigurationProperties(prefix = "weixin.spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "jobJdbcTemplate")
    public JdbcTemplate jobJdbcTemplate(@Qualifier("jobDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
  1. 使用方式:
    @Autowired
    @Qualifier("jobJdbcTemplate")
    protected JdbcTemplate jobJdbcTemplate;


    try {
        String password = "pwd";
        jobJdbcTemplate.update("insert into wx_union(userid, password,custid,loginid,type) values(?, ?, ?, ?, ?)", userId,password,custId,phone,"1");
    }catch (Exception e){
        Logger.recordLog("insertBindUser 失败: ", e.getMessage());
    }

你可能感兴趣的:(Springboot mysql 多数据源)