码云地址: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;
    }

  

 

转载于:https://www.cnblogs.com/yaohuiqin/p/9396583.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐