• springboot:mybatis多数据源配置


    1.application.properties

    #CMS数据源(主库)
    spring.datasource.cms.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.cms.url=jdbc:mysql://192.168.2.21:3306/cms?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
    spring.datasource.cms.username=root
    spring.datasource.cms.password=root123!@#
    spring.datasource.cms.max-active=20
    spring.datasource.cms.initial-size=1
    spring.datasource.cms.min-idle=3
    spring.datasource.cms.max-wait=60000
    spring.datasource.cms.time-between-eviction-runs-millis=60000
    spring.datasource.cms.min-evictable-idle-time-millis=300000
    spring.datasource.cms.test-while-idle=true
    spring.datasource.cms.test-on-borrow=false
    spring.datasource.cms.test-on-return=false
    spring.datasource.cms.poolPreparedStatements=true
    spring.datasource.cms.filters=stat,wall,slf4j
    
    #BASE数据源
    spring.datasource.base.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.base.url=jdbc:mysql://192.168.2.21:3306/base?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
    spring.datasource.base.username=root
    spring.datasource.base.password=root123!@#
    spring.datasource.base.max-active=20
    spring.datasource.base.initial-size=1
    spring.datasource.base.min-idle=3
    spring.datasource.base.max-wait=60000
    spring.datasource.base.time-between-eviction-runs-millis=60000
    spring.datasource.base.min-evictable-idle-time-millis=300000
    spring.datasource.base.test-while-idle=true
    spring.datasource.base.test-on-borrow=false
    spring.datasource.base.test-on-return=false
    spring.datasource.base.poolPreparedStatements=true
    spring.datasource.base.filters=stat,wall,slf4j

    2.配置主数据源

    import java.sql.SQLException;
    
    import javax.sql.DataSource;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.bind.RelaxedPropertyResolver;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.core.env.Environment;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    import com.alibaba.druid.pool.DruidDataSource;
    
    import net.common.utils.constant.ConstantCms;
    
    @Configuration
    @EnableTransactionManagement
    @MapperScan(basePackages = ConstantCms.MAPPER_PACKAGE, sqlSessionTemplateRef = "cmsSqlSessionTemplate")
    public class ConfigCmsDataSource implements EnvironmentAware {
    
      private Logger logger = LoggerFactory.getLogger(ConfigCmsDataSource.class);
    
      private RelaxedPropertyResolver propertyResolver;
    
      @Override
      public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.cms.");
      }
    
      @Bean(name = "cmsDataSource")
      @Primary
      public DataSource cmsDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(propertyResolver.getProperty("url"));
        datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
        datasource.setUsername(propertyResolver.getProperty("username"));
        datasource.setPassword(propertyResolver.getProperty("password"));
        if (StringUtils.isNotBlank(propertyResolver.getProperty("initial-size"))) {
          datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("min-idle"))) {
          datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("max-wait"))) {
          datasource.setMaxWait(Integer.valueOf(propertyResolver.getProperty("max-wait")));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("max-active"))) {
          datasource.setMaxActive((Integer.valueOf(propertyResolver.getProperty("max-active"))));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("min-evictable-idle-time-millis"))) {
          datasource.setMinEvictableIdleTimeMillis(
              Integer.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
        }
        try {
          datasource.setFilters("stat,wall");
        } catch (SQLException e) {
          logger.error("初始化BASE数据库连接池发生异常:{}", e.toString());
        }
        return datasource;
      }
    
      @Bean(name = "cmsSqlSessionFactory")
      @Primary
      public SqlSessionFactory cmsSqlSessionFactory(@Qualifier("cmsDataSource") DataSource cmsDataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(cmsDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ConstantCms.MAPPER_XML_PACKAGE));
        return bean.getObject();
      }
    
      @Bean(name = "cmsTransactionManager")
      @Primary
      public DataSourceTransactionManager cmsTransactionManager(@Qualifier("cmsDataSource") DataSource cmsDataSource) {
        return new DataSourceTransactionManager(cmsDataSource);
      }
    
      @Bean(name = "cmsSqlSessionTemplate")
      @Primary
      public SqlSessionTemplate cmsSqlSessionTemplate(
          @Qualifier("cmsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
      }
    
    }

    2.配置从数据源:没有 @Primary

    import java.sql.SQLException;
    
    import javax.sql.DataSource;
    
    import org.apache.commons.lang3.StringUtils;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.bind.RelaxedPropertyResolver;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.env.Environment;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    import com.alibaba.druid.pool.DruidDataSource;
    
    import net.common.utils.constant.ConstantBase;
    
    @Configuration
    @EnableTransactionManagement
    @MapperScan(basePackages = ConstantBase.MAPPER_PACKAGE, sqlSessionTemplateRef = "baseSqlSessionTemplate")
    public class ConfigBaseDataSource implements EnvironmentAware {
    
      private Logger logger = LoggerFactory.getLogger(ConfigBaseDataSource.class);
    
      private RelaxedPropertyResolver propertyResolver;
    
      @Override
      public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.base.");
      }
    
      @Bean(name = "baseDataSource")
      public DataSource baseDataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(propertyResolver.getProperty("url"));
        datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
        datasource.setUsername(propertyResolver.getProperty("username"));
        datasource.setPassword(propertyResolver.getProperty("password"));
        if (StringUtils.isNotBlank(propertyResolver.getProperty("initial-size"))) {
          datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("min-idle"))) {
          datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("max-wait"))) {
          datasource.setMaxWait(Integer.valueOf(propertyResolver.getProperty("max-wait")));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("max-active"))) {
          datasource.setMaxActive((Integer.valueOf(propertyResolver.getProperty("max-active"))));
        }
        if (StringUtils.isNotBlank(propertyResolver.getProperty("min-evictable-idle-time-millis"))) {
          datasource.setMinEvictableIdleTimeMillis(
              Integer.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
        }
        try {
          datasource.setFilters("stat,wall");
        } catch (SQLException e) {
          logger.error("初始化BASE数据库连接池发生异常:{}", e.toString());
        }
        return datasource;
      }
    
      @Bean(name = "baseSqlSessionFactory")
      public SqlSessionFactory baseSqlSessionFactory(@Qualifier("baseDataSource") DataSource baseDataSource)
          throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(baseDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ConstantBase.MAPPER_XML_PACKAGE));
        return bean.getObject();
      }
    
      @Bean(name = "baseTransactionManager")
      public DataSourceTransactionManager baseTransactionManager(@Qualifier("baseDataSource") DataSource baseDataSource) {
        return new DataSourceTransactionManager(baseDataSource);
      }
    
      @Bean(name = "baseSqlSessionTemplate")
      public SqlSessionTemplate baseSqlSessionTemplate(
          @Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
      }
    
    }

    3.注意扫描包路径和XML路径,红色标注部分,改成自己的。

    其中XML路径:classpath*:net/common/cms/mapper/xml/**/*.xml,第一个星号必不可少。

  • 相关阅读:
    shell
    Python全栈开发:django网络框架(二)
    Python全栈开发:django网络框架(一)
    动态规划问题以及诸多实例分析
    python实现并查集
    使用命令行编译和运行 c、Java和python程序
    整数除法操作的取整问题
    使用TensorFlow低级别的API进行编程
    使用TensorFlow高级别的API进行编程
    TensorFlow安装和HelloWorld
  • 原文地址:https://www.cnblogs.com/huiy/p/7243361.html
Copyright © 2020-2023  润新知