当前位置: 首页 > article >正文

(详细)Springboot 整合动态多数据源 这里有mysql(分为master 和 slave) 和oracle,根据不同路径适配不同数据源

文章目录

    • Springboot 整合多动态数据源 这里有mysql(分为master 和 slave) 和oracle
      • 1. 引入相关的依赖
      • 2. 创建相关配置文件
      • 3. 在相关目录下进行编码,不同路径会使用不同数据源

Springboot 整合多动态数据源 这里有mysql(分为master 和 slave) 和oracle

1. 引入相关的依赖

  <!--动态数据源-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>${dynamic-datasource.version}</version>
        </dependency>
          <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- oracle -->
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>${ojdbc.version}</version>
        </dependency>



2. 创建相关配置文件

package com.aspire.sc.base.data.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;

//import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class DataSourceConfig {

    @Bean(name = "master")
    @Qualifier("master")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.dynamic.datasource.master")
    public DataSource primaryDataSource(){
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "slave")
    @Qualifier("slave")
    @ConfigurationProperties(prefix="spring.datasource.dynamic.datasource.slave")
    public DataSource slave(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "oracleDataSource")
    @Qualifier("oracleDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.oracle")
    public DataSource oracleDataSource(){
        return DataSourceBuilder.create().build();
    }


}


package com.aspire.sc.base.data.config;

import com.aspire.common.dictenum.DictBaseEnum;
import com.aspire.common.dictenum.DictBaseItem;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
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;


/**
 * 数据库leadnews_article
 */
@Configuration
public class MysqlDataSourceConfig {

    @Bean
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("master") DataSource dataSource) throws Exception {
        return createSqlSessionFactory(dataSource);
    }

    @Bean
    public SqlSessionFactory mysqlSlaveSqlSessionFactory(@Qualifier("slave") DataSource dataSource) throws Exception {
        return createSqlSessionFactory(dataSource);
    }

    private SqlSessionFactory createSqlSessionFactory(DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);

        // 添加分页功能
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        sqlSessionFactory.setPlugins(new Interceptor[]{paginationInterceptor});

        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*/*.xml"));
        sqlSessionFactory.setTypeHandlersPackage("com.aspire.common.constant");
        sqlSessionFactory.setTypeEnumsPackage("com.aspire.common.constant," +
                "com.aspire.sc.base.data.domain.*.pojo," +
                "com.aspire.sc.base.data.constant");

        return sqlSessionFactory.getObject();
    }

    @Bean
    @Primary
    public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager(@Qualifier("master") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "slaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slave") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}


package com.aspire.sc.base.data.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;

@Configuration
//@MapperScan(basePackages = "com.aspire.sc.base.data.oracledomain.*", sqlSessionFactoryRef = "oracleSqlSessionFactory")
public class OracleDataSourceConfig {


    @Bean(name = "oracleSqlSessionFactory")
    public SqlSessionFactory oracleSqlSessionFactory(@Qualifier("oracleDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:oraclemapper/*.xml"));
        return sqlSessionFactory.getObject();

    }

    @Bean
    public SqlSessionTemplate oracleSqlSessionTemplate(@Qualifier("oracleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


    @Bean(name = "oracleTransactionManager")
    public DataSourceTransactionManager oracleTransactionManager(@Qualifier("oracleDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

启动文件加上:

import com.baomidou.dynamic.datasource.plugin.MasterSlaveAutoRoutingPlugin;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;


/**
 * @author wanggh
 */
@EnableConfigurationProperties
@ComponentScan({"com.aspire"})
@EnableTransactionManagement(proxyTargetClass = true)

@MapperScan(basePackages = {"com.aspire.sc.base.data.domain.*.mapper"}, sqlSessionFactoryRef = "mysqlSqlSessionFactory")
@MapperScan(basePackages = {"com.aspire.sc.base.data.oracledomain.mapper"}, sqlSessionFactoryRef = "oracleSqlSessionFactory")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ServletComponentScan
@EnableCaching
public class MsBaseDataApplication {

    public static void main(String[] args) {
        SpringApplication.run(MsBaseDataApplication.class, args);
    }
    /**
     * 纯的读写分离环境,写操作全部是master,读操作全部是slave
     * 默认主库名称master,从库名称slave。
     * 不用加@DS注解
     */
    @Bean
    public MasterSlaveAutoRoutingPlugin masterSlaveAutoRoutingPlugin() {
        return new MasterSlaveAutoRoutingPlugin();
    }

}

3. 在相关目录下进行编码,不同路径会使用不同数据源

在这里插入图片描述


http://www.kler.cn/a/517063.html

相关文章:

  • 2025年1月21日(树莓派点亮呼吸灯第一次修改)
  • 算法基础 -- 快速幂算法详解
  • 2025牛客寒假算法营2
  • 【Linux网络编程】传输层协议
  • Formality:不可读(unread)的概念
  • DRG/DIP 2.0时代下基于PostgreSQL的成本管理实践与探索(下)
  • Redis线上阻塞要如何排查
  • Java面向对象专题
  • 【leetcode100】二叉搜索树中第k小的元素
  • python远程获取数据库中的相关数据并存储至json文件
  • MySQL中的关联查询:方式、区别及示例
  • Python 爬虫——爬取Web页面图片
  • 03垃圾回收篇(D3_垃圾收集器的选择及相关参数)
  • 2K高刷电竞显示器怎么选?
  • 记忆层增强的 Transformer 架构:通过可训练键值存储提升 LLM 性能的创新方法
  • Django 静态文件配置实战指南
  • <keep-alive> <component ></component> </keep-alive>缓存的组件实现组件,实现组件切换时每次都执行指定方法
  • 详解Redis的Zset类型及相关命令
  • AviatorScript用法
  • 解决docker: ‘buildx‘ is not a docker command.
  • Golang初识
  • vue3中为什么引入setup,引入setup是为了解决什么问题,setup的执行时机是什么?返回值是什么
  • linux数据压缩
  • 14-6-1C++的list
  • Elixir语言的数据结构
  • 利用现有模型处理面部视频获取特征向量(4)