天天看點

SpringBoot MybatisPlus Druid 多資料源項目

寫在前面:本文主要介紹SpringBoot MybatisPlus和Druid這些元件下,如何建立多資料源(DataSource)的web項目。寫這篇部落格的原因就是我在搜尋同類型的問題的時候,其他人寫的部落格非常不清晰,完全無法按照介紹的步驟來實作。我希望我寫的這篇部落格可以真的替看這篇部落格的人能解決這類問題。如果你看完之後還是沒有解決可以評論留言,甚至加我的微信(JB328258)幫你解決。因為我覺得我們中國人寫技術部落格有的時候太敷衍了,不要把部落格當成一個記事本。而是要真正對不管是行業還是同樣的從業人員有價值才有意義。

背景: 我們的web項目需要讀取兩個資料庫裡面的表的資料,然後就有了這個需求。但是我在網上搜尋解決方法,很多人的部落格都是寫的連接配接兩個資料源,并且還通過AOP動态切換資料源,但是我認為這種使用場景應該是非常非常少的。一般情況下的應用場景都是表的資料在多個庫裡面。然後web項目需要讀多個庫的資料進行彙合。

正文:

第一步:引入對于的SpringBoot MybatisPlus Druid的Jar包。這一步不贅述,網上示例很多。

第二步:  填寫多個資料源的相關配置,如JDBC的連接配接位址,JDBC的資料庫等。

           1. cmdb代表一個資料庫。

           2. compass代表一個資料庫。

spring:
  datasource:
    cmdb:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.60.11:3306/cmdb_docker?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
      username: YourXXX
      password: YourXXX
      initial-size: 0
      min-idle: 1
      max-active: 20
      max-wait: 60000
      remove-abandoned: true
      remove-abandoned-timeout: 180
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      filters: stat,wall,log4j2
    compass:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.60.11:3306/compass?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
      username: YourXXX
      password: YourXXX
      initial-size: 0
      min-idle: 1
      max-active: 20
      max-wait: 60000
      remove-abandoned: true
      remove-abandoned-timeout: 180
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      filters: stat,wall,log4j2
           

第三步:建立對應的MybatisPlus的分頁插件如下

@Configuration
public class MybatisPlusConfig {

    /**
     * 分頁插件
     * @return
     */

    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

}
           

第四步:分别建立兩個DataSource對應的Config,注意看下面代碼裡面的備注,比較重要。

4.1 建立第一個DataSource的Config

//建立Compass資料的DataSource資料源
@Configuration
// basePackages 是掃描的Compass庫對應的Mapper
@MapperScan(basePackages = "com.ximalaya.compass.core.mapper",sqlSessionFactoryRef = "compassFactory")
public class CompassDataSourceConfig {


    @Autowired
    PaginationInterceptor paginationInterceptor;


    @Bean(name="compass")
    @ConfigurationProperties("spring.datasource.compass")
    public DataSource createCmdbDataSource(){
        return new DruidDataSource();
    }

    @Bean(name = "compassFactory")
    public SqlSessionFactory createCompassFactory(@Qualifier("compass") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        //這裡是配置Mybatis的Configuration
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);

        
        factoryBean.setConfiguration(configuration);
        //這裡是添加Mybatis的分頁插件
        factoryBean.setPlugins(new Interceptor[]{paginationInterceptor});

        //這裡是填寫Compass這個庫對應的Mapper.xml檔案
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-compass/*.xml"));
        return factoryBean.getObject();
    }

    @Bean(name = "compassSqlSessionTemplate")
    public SqlSessionTemplate createCompassSqlSessionTemplate(@Qualifier("compassFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
           

4.2 建立第二個DataSource的Config

@Configuration
@MapperScan(basePackages = "com.ximalaya.compass.collector.mapper",sqlSessionFactoryRef = "cmdbFactory")
public class CmdbDockerDataSourceConfig {

    @Autowired
    PaginationInterceptor paginationInterceptor;

    @Bean(name="cmdb_docker")
    @ConfigurationProperties("spring.datasource.cmdb")
    public DataSource createCmdbDataSource(){
        return new DruidDataSource();
    }

    @Bean(name = "cmdbFactory")
    public SqlSessionFactory createCmdbFactory(@Qualifier("cmdb_docker") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        factoryBean.setConfiguration(configuration);
        factoryBean.setPlugins(new Interceptor[]{paginationInterceptor});
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-cmdb/*.xml"));
        return factoryBean.getObject();
    }

    @Bean(name = "cmdbSqlSessionTemplate")
    public SqlSessionTemplate createCmdbSqlSessionTemplate(@Qualifier("cmdbFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
           

結尾:至此所有的建立和修改都完成,啟動SpringBoot項目使用對應的Service就可以通路對應的資料庫了。

繼續閱讀