springboot multiple data sources demo project

Background: The company wants to create a new data item, because you want to query data from multiple data sources, and did not do before the project build notes, this time to do a record. Out of the box, delicious Warning!

Build process encountered some problems, we will step instructions. Code Address: https://gitee.com/aaron_qc/multi-datasource.git

  1. First on the main course. Multi-step data source configuration
    1. Introducing dependent tkmapper + druid + mysql + spring-boot-configuration-processor
      1. <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>
        
        <!-- mysql and mybatis etc -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
    2. Configuration is as follows
      1. Start class plus @EnableConfigurationProperties.
        1. OceanApplication
          /**
           * @author QuCheng on 2019-09-16.
           * EnableConfigurationProperties 使 @ConfigurationProperties 注解的类(需要加@Component)生效。
           */
          @EnableConfigurationProperties
          @SpringBootApplication
          public class OceanApplication {
              public static void main(String[] args) {
                  SpringApplication.run(OceanApplication.class, args);
              }
          }
      2. yml configure properties
        1. application.yml custom name attribute, and only correspond to a corresponding class java
          Druid: 
            # data source configuration 
            User: the root 
            password: XXXX 
            driverClass: com.mysql.cj.jdbc.Driver 
            # Min Max initialization 
            initialSize:. 5 
            minIdle:. 5 
            for maxActive: 20 is 
            testOnBorrow: to false 
            urlIceberg: JDBC: MySQL: //106.12.176.120 ? / iceberg serverTimezone = GMT% 2B8 & characterEncoding = UTF-8 & useSSL = when false # set the time zone 
            urlOcean: jdbc: mysql: //106.12.176.120/ocean serverTimezone = GMT% 2B8 & characterEncoding = UTF-8 & useSSL = when false # set the time zone? 
            urlAccount: jdbc: MySQL :? //106.12.176.120/account serverTimezone = GMT% 2B8 & characterEncoding = UTF-8 & useSSL = false # set the time zone 
      3. Custom properties parent class loading BaseProperty
        1. Mapping yml configuration. 
          package com.hb.ocean.druid;
          
          import com.alibaba.druid.pool.DruidDataSource;
          import lombok.Data;
          import org.springframework.boot.context.properties.ConfigurationProperties;
          import org.springframework.stereotype.Component;
          
          import javax.sql.DataSource;
          
          /**
           * datasource base class
           * @author qucheng
           */
          @Data
          @ConfigurationProperties(prefix = "druid")
          @Component
          class BaseProperty {
          
              protected String user;
          
              protected String password;
          
              protected String driverClass;
          
              protected int initialSize;
          
              protected int maxActive;
          
              protected int minIdle;
          
              protected boolean testOnBorrow;
          
              protected String urlAccount;
          
              protected String urlOcean;
          
              protected String urlIceberg;
          
          
              DataSource createDataSource(String url) {
                  DruidDataSource dataSource = new DruidDataSource();
                  dataSource.setDriverClassName(driverClass);
                  dataSource.setUrl(url);
                  dataSource.setUsername(user);
                  dataSource.setPassword(password);
                  dataSource.setInitialSize(initialSize);
                  dataSource.setMaxActive(maxActive);
                  dataSource.setMinIdle(minIdle);
                  dataSource.setTestOnBorrow(testOnBorrow);
                  return dataSource;
              }
          }
      4. Their respective data source configuration map path (Mapper interfaces + xml file)
        1. Path Configuration - two other configurations will be omitted here
          com.hb.ocean.druid Package; 
          
          Import org.apache.ibatis.session.SqlSessionFactory; 
          Import org.mybatis.spring.SqlSessionFactoryBean; 
          Import org.springframework.beans.factory.annotation.Qualifier; 
          Import org.springframework.context.annotation .Bean; 
          Import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 
          Import org.springframework.jdbc.datasource.DataSourceTransactionManager; 
          Import org.springframework.stereotype.Component; 
          Import tk.mybatis.spring.annotation.MapperScan; 
          
          Import the javax. sql.DataSource; 
          
          / ** 
           * Account DataSource 
           * MapperScan (to use the table name mapping entity tk) annotations for binding packages and scan the specified data source, and the specified directory mapper process without adding annotations 
           * 
           * @ qucheng author 
           * / 
          @Component
          @MapperScan(basePackages = "com.hb.ocean.mapper.account", sqlSessionFactoryRef = "accountSqlSessionFactory")
          public class AccountConfig extends BaseProperty {
          
              @Bean(name = "accountDataSource")
              public DataSource createDataSource() {
                  return createDataSource(urlAccount);
              }
          
              @Bean(name = "accountTransactionManager")
              public DataSourceTransactionManager accountTransactionManager() {
                  return new DataSourceTransactionManager(createDataSource());
              }
          
              @Bean(name = "accountSqlSessionFactory")
              public SqlSessionFactory masterSqlSessionFactory(@Qualifier("accountDataSource") DataSource accountDataSource)
                      throws Exception {
                  final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
                  sessionFactory.setDataSource(accountDataSource);
                  String mapperLocation = "classpath:mapper/account/*.xml";
                  sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                          .getResources(mapperLocation));
                  return sessionFactory.getObject();
              }
          }
      5. Create a file in the appropriate directory. The project will be loaded at startup.
        1. Structure FIG.

           

    3. After the successful launch of the test results are as follows
      1. Test code
        com.hb.ocean.controller Package; 
        
        Import com.hb.ocean.mapper.account.UserMapper; 
        Import com.hb.ocean.mapper.iceberg.ItemOrderMapper; 
        Import org.springframework.web.bind.annotation.GetMapping; 
        Import ORG .springframework.web.bind.annotation.RequestMapping; 
        Import org.springframework.web.bind.annotation.RestController; 
        
        Import javax.annotation.Resource; 
        
        / ** 
         * @author QuCheng ON 2019-09-17. 
         * / 
        @RestController 
        @ @RequestMapping ( "/ QC") 
        public class the TestView { 
        
            / ** 
             * not recommended Dao layer directly introduced into the controller layer. Here only demonstrate the use of 
             * / 
            @Resource 
            Private UserMapper UserMapper;  
            @Resource
            Private ItemOrderMapper itemOrderMapper;
        
            @GetMapping("/test")
            public String test() {
                System.out.println("用户数:" + userMapper.selectCountUser(null, null));
                System.out.println("订单数:" + itemOrderMapper.selectCountSuccessOrder(null, null));
                return "ok";
            }
        }
      2. Test Results

Some questions also arise over process

  1. A plurality of data sources yml share the basic configuration, in addition to the data source url inconsistent.
  2. Custom configuration items need yml property
    1. 引入spring-boot-configuration-processor。
    2. Start class uses the annotation @EnableConfigurationProperties
    3. Parsing class 3 to be introduced into the above comment @Data for convenience only. @ConfigurationProperties (prefix = "druid") is specified read "druid" start properties. @Component represented by the container management
  3. Configuration class @MapperScan annotations are used tk.mybatis.spring.annotation.MapperScan comment. org.mybatis.spring.annotation.MapperScan can also be used, but it can not be used in conjunction @Table annotation map.

Process springboot multi data source configuration as described above. This is a demo version. Further relates to the practical application of data

  1. eureka discovery of registration. Start the introduction of class notes
  2. feign interface calls and failed fuse
  3. Elegantly simple process shutdown
  4. swagger document
  5. redis Distributed Transaction

 

Guess you like

Origin www.cnblogs.com/nightOfStreet/p/11543768.html