zoukankan      html  css  js  c++  java
  • 微服务 第七章 SpringBoot多数据源的配置(通过JdbcTemplate的方式)

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

      

  • 相关阅读:
    ELK安装(ubuntu)
    Ubuntu18.04上安装java
    .net core跨平台的文件路径
    缺少vim
    docker进入容器
    docker删除名字为none的imgae
    Ubuntu18.04上安装Docker-Compose
    Java类的反射
    Java常用类(二) Scanner类和大数类
    Java常用类(一)Math类和Random类
  • 原文地址:https://www.cnblogs.com/yaohuiqin/p/9396583.html
Copyright © 2011-2022 走看看