spring boot에서 아주 간단히 multi-datasource를 관리하고 jdbctemplate를 사용할 수 있는 예제를 소개한다.





먼저 maven또는 gradle 파일의 dependency에 db의 driver, spring-boot-starter-jdbc, commons-dbcp2를 추가한다.


build.gradle

compile("mysql:mysql-connector-java:5.1.36")
compile("org.springframework.boot:spring-boot-starter-jdbc")
compile("org.apache.commons:commons-dbcp2:2.1.1")


application.yml

spring:
profiles : dev
activity_slave_db_0:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://db0.google.com:3306/test
username: develop
password : devteam
max-wait : 10000
max-active : 5
test-on-borrow: true
validationQuery: select 1
activity_slave_db_1:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://db1.google.com:3306/test
username: develop
password : devteam
max-wait : 10000
max-active : 5
test-on-borrow: true
validationQuery: select 1



Datasource 설정 

import org.springframework.beans.factory.annotation.Autowired;
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 DatabaseConfig {

@Primary @Bean(name = "dsSlave0")
@ConfigurationProperties(prefix="spring.activity_slave_db_0")
public DataSource dsSlave0() {
return DataSourceBuilder.create().build();
}

@Bean(name = "dsSlave1")
@ConfigurationProperties(prefix="spring.activity_slave_db_1")
public DataSource dsSlave1() {
return DataSourceBuilder.create().build();
}

@Bean(name = "jdbcSlave0")
@Autowired
public JdbcTemplate slave0JdbcTemplate(@Qualifier("dsSlave0") DataSource dsSlave) {
return new JdbcTemplate(dsSlave);
}

@Bean(name = "jdbcSlave1")
@Autowired
public JdbcTemplate slave1JdbcTemplate(@Qualifier("dsSlave1") DataSource dsSlave) {
return new JdbcTemplate(dsSlave);
}

}




실제 DAO에서 사용하는 jdbctemplate 코드.

@Component
public class ActivitySlaveDao {
@Autowired
@Qualifier("jdbcSlave0")
private JdbcTemplate jdbcTemplate0;
@Autowired
@Qualifier("jdbcSlave1")
private JdbcTemplate jdbcTemplate1;
private List<JdbcTemplate> getJdbcTemplates() {
List list = Lists.newArrayList();
list.add(jdbcTemplate0);
list.add(jdbcTemplate1); }

// .. jdbcTemplate 사용. }


Posted by '김용환'
,