Spring Boot's JdbcTemplate multiple data source configuration and use

Multiple data source configuration Create a Spring configuration class that defines two DataSources to read different configurations in application.properties. In the following example, the cold backup data source is configured with the configuration starting with spring.datasource.cold

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.properties

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

The support for JdbcTemplate is relatively simple. You only need to inject the corresponding datasource into it. In the following example, when creating a JdbcTemplate, inject a datasource named coldJdbcTemplate to distinguish different JdbcTemplates.

use

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";
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326004284&siteId=291194637