springboot配置双数据源

2022-10-07 13:38:22

第一数据源

package com.test.demo.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.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/**
 * Created by kaixuan on 2018/5/4.
 */@Configuration//MapperScan指定dao@MapperScan(basePackages ="com.test.demo.dao.primary", sqlSessionFactoryRef ="primarySqlSessionFactory")publicclassPrimaryDatasourceConfig {/**
     * 主数据库 连接mysql
     * @return
     */@Bean(name ="primaryDataSource")@ConfigurationProperties(prefix ="spring.datasource.druid.primary")@Primarypublic DataSourceprimaryDataSource() {return DataSourceBuilder.create().build();
    }/**
     * 配置session工厂
     * @param dataSource
     * @return
     * @throws Exception
     */@Bean(name ="primarySqlSessionFactory")@Primarypublic SqlSessionFactoryprimarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource)throws Exception {
        SqlSessionFactoryBean bean =new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/primary/**/*Mapper.xml"));//指定mapperreturn bean.getObject();
    }/**
     * 配置事物管理器
     * @param dataSource
     * @return
     */@Bean(name ="primaryTransactionManager")@Primarypublic DataSourceTransactionManagerprimaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {returnnew DataSourceTransactionManager(dataSource);
    }/**
     * 模板
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */@Bean(name ="primarySqlSessionTemplate")@Primarypublic SqlSessionTemplateprimarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory)throws Exception {returnnew SqlSessionTemplate(sqlSessionFactory);
    }
}

第二数据源

package com.test.demo.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.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;/**
 * Created by kaixuan on 2018/5/4.
 */@Configuration@MapperScan(basePackages ="com.test.demo.dao.secondary", sqlSessionFactoryRef ="secondarySqlSessionFactory")publicclassSecondaryDatasourceConfig {/**
     * 第二数据库源 用于连接sqlserver
     * @return
     */@Bean(name ="secondaryDataSource")@ConfigurationProperties(prefix ="spring.datasource.druid.secondary")//    @Primarypublic DataSourcesecondaryDataSource() {return DataSourceBuilder.create().build();
    }/**
     * 配置session工厂
     * @param dataSource
     * @return
     * @throws Exception
     */@Bean(name ="secondarySqlSessionFactory")//    @Primarypublic SqlSessionFactorysecondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource)throws Exception {
        SqlSessionFactoryBean bean =new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/secondary/**/*Mapper.xml"));return bean.getObject();
    }/**
     * 配置事物管理器
     * @param dataSource
     * @return
     */@Bean(name ="secondaryTransactionManager")//    @Primarypublic DataSourceTransactionManagersecondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {returnnew DataSourceTransactionManager(dataSource);
    }/**
     * 模板
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */@Bean(name ="secondarySqlSessionTemplate")//    @Primarypublic SqlSessionTemplatesecondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory)throws Exception {returnnew SqlSessionTemplate(sqlSessionFactory);
    }
}

配置文件

#数据库,暂时没有集成连接池
spring:
  datasource:#整合连接池type: com.alibaba.druid.pool.DruidDataSource
    druid:
      primary:
        url: jdbc:mysql://localhost:3306/mes?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=UTF8&useSSL=false#    url: jdbc:mysql:///mes?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=UTF8&useSSL=false
        username: test
        password: test
        driver-class-name: com.mysql.jdbc.Driver

        minIdle:1
        maxIdle:20
        maxActive:100
        initialSize:10
        timeBetweenEvictionRunsMillis:3000
        minEvictableIdleTimeMillis:300000
        validationQuery: SELECT'ZTM' FROM DUAL
        validationQueryTimeout:10000
        testWhileIdle:true
        testOnBorrow:false
        testOnReturn:false
        maxWait:60000# 打开PSCache,并且指定每个连接上PSCache的大小
        poolPreparedStatements:true
        maxPoolPreparedStatementPerConnectionSize:20
        filters: stat,wall,log4j2
      secondary:
        url: jdbc:sqlserver://localhost:1433; DatabaseName=EDO
        username: test
        password: test
        driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

        minIdle:1
        maxIdle:20
        maxActive:100
        initialSize:10
        timeBetweenEvictionRunsMillis:3000
        minEvictableIdleTimeMillis:300000
        validationQuery: SELECT'ZTM' FROM DUAL
        validationQueryTimeout:10000
        testWhileIdle:true
        testOnBorrow:false
        testOnReturn:false
        maxWait:60000# 打开PSCache,并且指定每个连接上PSCache的大小
        poolPreparedStatements:true
        maxPoolPreparedStatementPerConnectionSize:20
        filters: stat,wall,log4j2#    redis:#        database: 0#        password:#        pool:#          max-active: 200#          max-wait: -1#          max-idle: 20#          min-idle: 0#        timeout: 0#  activiti:#    check-process-definitions: false#设置日志级别,打印sql#logging:#    level:#        com:#            example:#                demo: DEBUG#    pattern:#        console: '%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n'#        file: '%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n'#更改端口
server:
  port:8089

path:
  uploadPath: D:\excel\
  downloadPath: D:\excel\
  importloadPath: D:\excel\
  exportloadPath: D:\excel\

启动类

@SpringBootApplication@EnableCaching@EnableConfigurationProperties@ServletComponentScan@ComponentScan(basePackages ="com.test.demo")publicclassMesApplication {publicstaticvoidmain(String[] args) {
        SpringApplication.run(MesApplication.class, args);
    }
}
  • 作者:不急god
  • 原文链接:https://zhangsl.blog.csdn.net/article/details/80262589
    更新时间:2022-10-07 13:38:22