spring boot 配置多数据源

1.application.yml配置

server:
  port: 8088
spring:
    http:
      multipart:
        max-file-size: 50Mb
        max-request-size: 50Mb
        enabled: true
    datasource:
      primary:
        name: test
        url: jdbc:mysql://116.62.23.45:3306/asd2?useUnicode=true&characterEncoding=UTF-8
        username: root
        password: 123456
        #url: jdbc:mysql://118.31.37.175:3306/asd_dev?useUnicode=true&characterEncoding=UTF-8
        #username: root
        #password: zhezhuo408
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20


    #数据源2
      secondary:
        name: test
        url: jdbc:mysql://116.62.23.45:3306/asd_test1?useUnicode=true&characterEncoding=UTF-8
        username: root
        password: 123456
        #url: jdbc:mysql://118.31.37.175:3306/asd_dev?useUnicode=true&characterEncoding=UTF-8
        #username: root
        #password: zhezhuo408
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
    redis:
      host: 127.0.0.1
      port: 6379
    application:
      name: webapi
mybatis:
  mapper-locations: classpath:mapping/**/*.xml
  type-aliases-package: com.aishidai.app.model.pojo.*
  check-config-location: true
  config-location: classpath:mybatis-config.xml
logging:
  level:
    org.springframework.web: DEBUG
    com.aishidai.app.dao: DEBUG
alishidai: testHolleWrod
ribbon:
  eager-load:
    enabled: false

2.写两个数据源类

ALLMybatisConfig:

package com.aishidai.app.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @MapperScan来扫描注册mybatis数据库接口类,其中basePackages属性表明接口类所在的包,
 * sqlSessionTemplateRef表明接口类使用的SqlSessionTemplate(MyBatis提供的持久层访问模板化的工具,
 * 线程安全,
 * 可通过构造参数或依赖注入SqlSessionFactory实例)。如果项目需要配置两个数据库,
 * @MapperScan也需要分别配置。
 */
@Configuration
@MapperScan(basePackages = {"com.aishidai.app.dao"},sqlSessionTemplateRef = "allSqlSessionTemplate")
public class AllMybatisConfig {

    @Bean(name="allDataSource")
    @Primary//必须加此注解,不然报错,下一个类则不需要添加,@Primary注解的实例优先于其他实例被注入
    //SpringBoot 是通過@ConfigurationProperties來获取配置信息,
    // @ConfigurationProperties 使用方式有两种 1、在类上使用该注解 2、在工厂方法上使用该注解 (@bean)
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource allDataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean//@Qualifier限定描述符除了能根据名字进行注入,更能进行更细粒度的控制如何选择候选者
    public SqlSessionFactory allSqlSessionFactory(@Qualifier("allDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //添加xml目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
       try {
             bean.setMapperLocations(resolver.getResources("classpath*:mapping/**/*.xml"));
             return bean.getObject();
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException(e);
                }
    }
    @Bean
    public SqlSessionTemplate allSqlSessionTemplate(@Qualifier("allSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        //使用上面配置的Facyory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }

}

OrderMybatisConfig:

package com.aishidai.app.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * 配置数据源2
 */
@Configuration
@MapperScan(basePackages = {"com.aishidai.app.dao1"},sqlSessionTemplateRef = "orderSqlSessionTemplate")
public class OrderMybatisConfig {

    @Bean("orderDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource orderDataSource(){
     return DataSourceBuilder.create().build();
}
  @Bean
  public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
  }
  @Bean
  public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception{
      SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
      bean.setDataSource(dataSource);
      //添加xml目录
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      try {
          bean.setMapperLocations(resolver.getResources("classpath:mapping1/*.xml"));
          return bean.getObject();
      } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException(e);
      }

  }


}

3.启动类配置

package com.aishidai.app.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
              
/**
 * Springboot 启动类
 */
@SpringBootApplication
@ServletComponentScan(basePackages = "com.aishidai")
@ComponentScan(basePackages = "com.aishidai")
@EnableCaching //开启缓存
//@MapperScan(basePackages = {"com.aishidai.app.dao"})//扫描 包下相应的class 主要是mybatis 的持久化类
//@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class App {

   public static void main(String[] args) {
      System.out.printf("================开始启动===========");
      SpringApplication.run(App.class, args);
   }
}

4.具体的例子不再书写

猜你喜欢

转载自blog.csdn.net/xfy18317776108/article/details/83268941