SpringBoot多數據源配置

  • 多數據源介紹
    現在很多公司的系統都不是單一的,可能會與其他系統對接,甚至與其他公司系統對接,公司項目一直都有多數據源配置的功能,但是一直沒用過,前段時間,在給政府的項目中需要對接政府得另一套系統,我們系統是mysql,他們是sqlserver,就需要在配置一個數據源。很簡單就是寫一些配置類,下面我們以JdbcTemplate和Jpa的方式來配置。用兩臺主機上的庫。一臺雲主機,一臺本地。

  • yml文件配置
    配置三個數據源。一臺雲主機上的mysql,兩個本地庫都是mysql,如果是其他數據庫原理一樣。

spring:
    datasource:

        druid:
            first:
                url: jdbc:mysql://localhost:3306/annotation?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
                username: root
                password: XXX
                type: com.alibaba.druid.pool.DruidDataSource
                driver-class-name: com.mysql.jdbc.Driver
            second:
                url: jdbc:mysql://XXXXXXXXX:3306/log?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
                username: root
                password: XXX
                type: com.alibaba.druid.pool.DruidDataSource
                driver-class-name: com.mysql.jdbc.Driver
            third:
                url: jdbc:mysql://localhost:3306/third?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
                username: root
                password: root
                type: com.alibaba.druid.pool.DruidDataSource
                driver-class-name: com.mysql.jdbc.Driver
            initial-size: 10
            max-active: 100
            min-idle: 10
            max-wait: 60000
            pool-prepared-statements: true
            max-pool-prepared-statement-per-connection-size: 20
            time-between-eviction-runs-millis: 60000
            min-evictable-idle-time-millis: 300000
            validation-query: SELECT 1 FROM DUAL
            test-while-idle: true
            test-on-borrow: false
            test-on-return: false
            stat-view-servlet:
                enabled: true
                url-pattern: /druid/*
            filter:
                stat:
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: true
  • pom文件配置
    mysql連接,alibaba的數據庫連接池druid。
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.26</version>
        </dependency>
         <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

  • 配置類
package com.example.demo.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 org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @Description:
 * @author: lihaitao
 * @create 2018/11/13 下午7:35
 **/
@Configuration
public class DataSourceConfig {
	//第一個數據源
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.druid.first")//指定yml中的對應數據庫配置
    @Primary            //默認主數據源
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }
    @Bean(name = "aliyun")
    @Qualifier("aliyun")
    @ConfigurationProperties(prefix="spring.datasource.druid.second")//指定yml中的對應數據庫配置
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }
//
    @Bean(name = "thirdDataSource")
    @Qualifier("thirdDataSource")
    @ConfigurationProperties(prefix="spring.datasource.druid.third")//指定yml中的對應數據庫配置
    public DataSource thirdDataSource() {
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }
}

上面配置了三個數據源,下面就是將除主數據源以外的連個數據源注入到JdbcTemplate中。

  • 阿里雲主機的數據源注入

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @Description JDBCTemplateConfig:
 * @Author LiHaitao
 * @Date 2018/11/14 10:31
 **/
@Configuration
@Import(DataSourceConfig.class)
public class AliyunJDBCTemplateConfig {

    @Resource(name = "aliyun")
    private DataSource dataSource;

    @Bean(name = "aliyunJDBCTemplate")
    public JdbcTemplate jdbcTemplate(){
        return new JdbcTemplate(dataSource);
    }
}

  • 第三個數據源注入
@Configuration
@Import(DataSourceConfig.class)
public class ThirdJDBCTemplateConfig {

    @Resource(name = "thirdDataSource")
    private DataSource dataSource;

    @Bean(name = "thirdSourceJDBCTemplate")
    public JdbcTemplate jdbcTemplate(){
        return new JdbcTemplate(dataSource);
    }
}
  • 在dao中使用Jdbctemplate指定數據源並操作數據庫
@Repository
@Slf4j
public class SuperviseRecordDaoImpl implements SuperviseRecordDao {

    @Autowired
    @Qualifier("aliyunJDBCTemplate")//指定數據源
    private JdbcTemplate sqlServerJdbcTemplate;



    public List<SuperviseRecord> getSuperviseRecords(Long id) {
        if (null==id){
            log.info("id爲空,name:{}",id);
            return null;
        }
        String sql = "SELECT * FROM suprivise WHERE id=?";
        List<SuperviseRecord> superviseRecordList = sqlServerJdbcTemplate.query(sql, new SuperviseRecordMapper(), id);
        if (superviseRecordList==null){
            log.error("getSuperviseRecords查詢失敗");
        }
        return superviseRecordList;
    }

    class SuperviseRecordMapper implements RowMapper<SuperviseRecord> {
        @Override
        public SuperviseRecord mapRow(ResultSet resultSet, int i) throws SQLException {
            SuperviseRecord superviseRecord=new SuperviseRecord();
            superviseRecord.setCreateCode(resultSet.getString("create_code"));
            superviseRecord.setCreateName(resultSet.getString("create_name"));
            superviseRecord.setId(resultSet.getLong("id"));
            return superviseRecord;
        }
    }


}


/**
* @Description:
* @Author:         Lihaitao
* @Date:       2018/11/12 11:07
*/
@Repository
@Slf4j
public class RecordDaoImpl implements RecordDao {

    @Autowired
    @Qualifier("thirdSourceJDBCTemplate")
    private JdbcTemplate sqlServerJdbcTemplate;
    public List<Record> getSuperviseRecords(Long id) {
        if (null==id){
            log.info("id爲空,name:{}",id);
            return null;
        }
        String sql = "SELECT * FROM record WHERE id=?";
        List<Record> superviseRecordList = sqlServerJdbcTemplate.query(sql, new SuperviseRecordMapper(), id);
        if (superviseRecordList==null){
            log.error("getSuperviseRecords查詢失敗");
        }
        return superviseRecordList;
    }

    class SuperviseRecordMapper implements RowMapper<Record> {
        @Override
        public Record mapRow(ResultSet resultSet, int i) throws SQLException {
            Record superviseRecord=new Record();
            superviseRecord.setCreateCode(resultSet.getString("create_code"));
            superviseRecord.setCreateName(resultSet.getString("create_name"));
            superviseRecord.setId(resultSet.getLong("id"));
            return superviseRecord;
        }
    }


}

  • 總結
    通過配置數據源,注入JdbcTempalte中就可以使用主數據源以外的兩個數據源操作了,主數據源使用jpa不用注入,直接操作就是默認的數據源。
    完整代碼:https://github.com/lihaitao1418064017/aspect.git
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章