springboot通过JdbcTemplate实现多数据库

pom.xml

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

application.properties:

spring.datasource.primary.jdbc-url=jdbc:sqlserver://localhost:1433;DatabaseName=spiderdb
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

spring.datasource.secondary.jdbc-url=jdbc:sqlserver://localhost:1434;DatabaseName=spiderdb
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
spring.datasource.secondary.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

#注意使用url,可能出现"java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName."错误.

TwoDataSourceConfig:

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

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

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

@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource" ) DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}

测试验证:

@RunWith(SpringRunner.class)
@SpringBootTest
public class JdbcTest {

@Autowired
@Qualifier("primaryJdbcTemplate")
protected JdbcTemplate pjdbcTemplate;

@Autowired
@Qualifier("secondaryJdbcTemplate")
protected JdbcTemplate sjdbcTemplate;

@Test
public void test() throws Exception {
String a = pjdbcTemplate.queryForObject("select count(*) from xx where tag = '3' ", String.class);
String b = sjdbcTemplate.queryForObject("select count(*) from xx where tag = '3' ", String.class);
Assert.assertEquals(a, b);
}
}

 

posted @ 2018-06-21 14:06  一路漂泊  阅读(1681)  评论(0编辑  收藏  举报