码云地址:https://gitee.com/yaohuiqin/SpringBootDemo
1、在application.properties 文件中配置连接参数:
spring.datasource.primary.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.primary.username=microservice
spring.datasource.primary.password=microservice
spring.datasource.primary.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.secondary.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.secondary.username=microservice2
spring.datasource.secondary.password=microservice2
spring.datasource.secondary.driver-class-name=oracle.jdbc.driver.OracleDriver
2、在项目启动类下创建配置类:
/**
* 多数据源配置
*/
@Configuration
public class DataSourceConfig {
//配置第一个数据源
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
//配置第二个数据源
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
3、使用方式,在service方法中调用:
@Service
public class UserOperateServiceImpl implements UserOperateService {
@Autowired
@Qualifier("primaryJdbcTemplate")
private JdbcTemplate primaryJdbcTemplate;
@Autowired
@Qualifier("secondaryJdbcTemplate")
private JdbcTemplate secondaryJdbcTemplate;
@Override
public List<User> getAllUsersbyprimaryJdbcTemplate() {
List list = primaryJdbcTemplate.queryForList("SELECT userId,NAME, AGE FROM tableuser");
return list;
}
@Override
public List<User> getAllUsersbysecondaryJdbcTemplate() {
List list = secondaryJdbcTemplate.queryForList("SELECT userId,NAME, AGE FROM tableuser");
return list;
}
所有评论(0)