Spring Boot之JdbcTemplate多數據源配置與使用

多數據源配置 建立一個Spring配置類,定義兩個DataSource用來讀取application.properties中的不一樣配置。以下例子中,冷備份數據源配置爲spring.datasource.cold開頭的配置java

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.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
 
@Configuration
public class DataSourceConfig {

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

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

application.propertiesmysql

spring.datasource.cold.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.cold.url=jdbc:mysql://192.168.1.94:3308/db_cold?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.cold.username=admin
spring.datasource.cold.password=123456
spring.datasource.cold.driver-class-name=com.mysql.jdbc.Driver

對JdbcTemplate的支持比較簡單,只須要爲其注入對應的datasource便可,以下例子,在建立JdbcTemplate的時候注入名爲coldJdbcTemplate數據源來區分不一樣的JdbcTemplate。web

使用spring

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value="/datatrans")
@Api(value = "/datatrans", description = "冷熱數據遷移API", position = 1)
public class DatatransColdController {

    @Autowired
    @Qualifier("coldJdbcTemplate")
    protected JdbcTemplate coldJdbcTemplate;

    @RequestMapping(value="/testJDBCTemple",method = RequestMethod.GET)
    public String testJDBCTemple() throws Exception {
        coldJdbcTemplate.execute("SELECT * FROM  PROJECT WHERE PROJECT_ID=1");
        return "SUCCESS";
    }

}
相關文章
相關標籤/搜索