1. 程式人生 > >SpringBoot使用JdbcTemplate的雙資料來源配置

SpringBoot使用JdbcTemplate的雙資料來源配置

資料來源配置:

spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.primary.url=jdbc:mysql://read:3306/sevend?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false
spring.datasource.primary.username=aaa
spring.datasource.primary.password=aaa
spring.datasource.primary.max-active=40
spring.datasource.primary.max-idle=5
spring.datasource.primary.min-idle=5
spring.datasource.primary.initial-size=5

spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.secondary.url=jdbc:mysql://write:3306?useUnicode=true&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false
spring.datasource.secondary.username=root
spring.datasource.secondary.password=
spring.datasource.secondary.max-active=10
spring.datasource.secondary.max-idle=5
spring.datasource.secondary.min-idle=5
spring.datasource.secondary.initial-size=5

然後讓spring boot幫你例項化兩個dataSource並分別注入到兩個JdbcTemplate中

package com.dafy.sevend.boss.customer.manager.dao;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;

@Configuration
public class DataSourceConfig {
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource(){
        return DataSourceBuilder.create().build();
    }

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

    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource")DataSource secondaryDataSource){
        return new JdbcTemplate(secondaryDataSource);
    }
}
使用的時候直接在dao層注入你要使用的JdbcTemplate即可
    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Autowired
    @Qualifier("secondaryJdbcTemplate")
    private JdbcTemplate writableJdbcTemplate;