Spring Boot 多数据源配置

Spring Boot 多数据源配置

本文主要介绍了,SpringBoot框架下集成mybatis的多数据源配置,一下展示了mysql和sqlserver两种数据库的链接方式。

1、添加SpringBoot多数据源的配置文件,以下链接了mysql和sqlserver两个数据源。

spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/test_joins?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=60000

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test1
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initial-size=5
spring.datasource.max-active=20
spring.datasource.min-idle=5
spring.datasource.max-wait=60000

2、添加mybatis的maven依赖

	
				com.baomidou
				mybatis-plus
				2.1.7
			
	
				com.baomidou
				mybatisplus-spring-boot-starter
				1.0.5
			

3、名词解释

  • SqlSessionTemplate:是MyBatis-Spring的核心。这个类负责管理MyBatis的SqlSession,调用MyBatis的SQL方法,翻译异常。SqlSessionTemplate是线程安全的,可以被多个DAO所共享使用。SqlSessionTemplate管理session的生命周期、包含必要的关闭、提交和回滚操作。
  • sqlSessionTemplateRef:指定数据源对应的SqlSessionTemplate
  • MAPPER_LOCATION:"classpath*:/mapper/sysmodle/**Mapper.xml"  数据源对应mybatis的xml文件路径
  • TYPE_ALIASES_PACKAGE:com.fcbox.dechg.domain.sysmodle  数据源对应mybatis对应的实体路径
  • DataSourceTransactionManager:某个数据源的事物配置
  • @Qualifier("dataSourceServer") DataSource: 多数据源注入是可以通过定义bean的名称,以byName方式寻找合格的bean,这样就消除了byType方式产生的歧义,多数据源中存在多个类型相同的DataSource,通过@Qualifier定义name来消除歧义。
  • @Primary:在众多相同的bean中,优先选择用@Primary注解的bean(该注解加在各个bean上)

4、如下是mysql数据源链接的代码:

package com.fcbox.dechg.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
//import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
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 org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * Created by 000376 on 2018/2/3.
 */
@Configuration
@MapperScan(basePackages = {"com.fcbox.dechg.mapper.sysmodle"}, sqlSessionTemplateRef = "userSqlSessionTemplate")
public class MybatisPlusConfig {

    private static final String MAPPER_LOCATION = "classpath*:/mapper/sysmodle/**Mapper.xml";

    private static final String TYPE_ALIASES_PACKAGE = "com.fcbox.dechg.domain.sysmodle";

    /**
     * @Description : druid注入
     * ---------------------------------
     */
    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.druid.")
    public DataSource dataSource() {
        DataSource dataSourceServer = DruidDataSourceBuilder
                .create()
                .build();
        return dataSourceServer;
    }


    @Bean(name = "sqlSessionFactoryFirst")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource,
                                               @Qualifier("pageInterceptor") PageInterceptor pageInterceptor) throws Exception {
        final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //实体扫描
        sessionFactory.setTypeAliasesPackage(MybatisPlusConfig.TYPE_ALIASES_PACKAGE);
        //mapper-locations
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MybatisPlusConfig.MAPPER_LOCATION));
        sessionFactory.setPlugins(new Interceptor[]{pageInterceptor});
        return sessionFactory.getObject();
    }


    //事物构建
    @Bean(name = "transactionManagerFirst")
    @Primary
    public DataSourceTransactionManager TransactionManagerFirst(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    //SqlSessionTemplate是线程安全的,可以被多个DAO所共享使用。
    @Bean
    @Primary
    public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("sqlSessionFactoryFirst") SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory); // 使用上面配置的Factory
        return template;
    }


    /***
     * plus 的性能优化
     * @return
     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        PerformanceInterceptor performanceInterceptor=new PerformanceInterceptor();
//        /**/
//        //        performanceInterceptor.setMaxTime(1000);
//        /**/
//        performanceInterceptor.setFormat(true);
//        return performanceInterceptor;
//    }

    /**
     * @Description : mybatis-plus分页插件
     * ---------------------------------
     */
/*    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setLocalPage(true);
        page.setDialectType("mysql");
        return page;
    }*/
}

5、sqlserver数据源配置

package com.fcbox.dechg.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
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 org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

//import com.baomidou.mybatisplus.plugins.PaginationInterceptor;

/**
 * Created by 000376 on 2018/2/3.
 */
@Configuration
@MapperScan(basePackages = {"com.fcbox.dechg.mapper.oaflows"}, sqlSessionTemplateRef = "SqlSessionTemplateSer")
public class MybatisPlusConfig_Server {

    private static final String MAPPER_LOCATION = "classpath*:/mapper/oaflows/*Mapper.xml";

    private static final String TYPE_ALIASES_PACKAGE = "com.fcbox.dechg.domain.oaflows";

    /**
     * @Description : druid注入
     * ---------------------------------
     */
    @Bean
    @ConfigurationProperties("spring.datasource")
    @Qualifier("dataSourceServer")
    public DataSource dataSourceServer() {
         DataSource dataSourceServer = DataSourceBuilder
                .create()
                .build();
          return dataSourceServer;
    }

    @Bean(name = "sqlSessionFactoryServer")
    public SqlSessionFactory sqlSessionFactoryServer(@Qualifier("dataSourceServer") DataSource dataSourceServer,
                                                     @Qualifier("pageInterceptor") PageInterceptor pageInterceptor) throws Exception {
        final MybatisSqlSessionFactoryBean sqlSessionFactoryServer = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryServer.setDataSource(dataSourceServer);
        //实体扫描
        sqlSessionFactoryServer.setTypeAliasesPackage(MybatisPlusConfig_Server.TYPE_ALIASES_PACKAGE);
        //mapper-locations
        sqlSessionFactoryServer.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MybatisPlusConfig_Server.MAPPER_LOCATION));
        sqlSessionFactoryServer.setPlugins(new Interceptor[]{pageInterceptor});
        return sqlSessionFactoryServer.getObject();
    }

    @Bean(name = "transactionManagerServer")
    public DataSourceTransactionManager TransactionManagerServer(@Qualifier("dataSourceServer") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate SqlSessionTemplateSer(@Qualifier("sqlSessionFactoryServer") SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory); // 使用上面配置的Factory
        return template;
    }




    /***
     * plus 的性能优化
     * @return
     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        PerformanceInterceptor performanceInterceptor=new PerformanceInterceptor();
//        /**/
//        //        performanceInterceptor.setMaxTime(1000);
//        /**/
//        performanceInterceptor.setFormat(true);
//        return performanceInterceptor;
//    }

    /**
     * @Description : mybatis-plus分页插件
     * ---------------------------------
     */
/*    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setLocalPage(true);
        page.setDialectType("mysql");
        return page;
    }*/
}

 

你可能感兴趣的:(java)