展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > SpringBoot多数据源切换怎么实现

SpringBoot多数据源切换怎么实现

配置文件(YML)spring:datasource:default-db-key:voidmemulti-db:-voidme:driver-class-name:com.mysql.cj.jdbc.Driverusername:rootpassword:rooturl:jdbc:mysql://192.168.42.153:3306/voidme?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&maxReconnects

本文目录

      配置文件(YML)

      spring:
        datasource:
          default-db-key: voidme
          multi-db:
            - voidme:
                driver-class-name: com.mysql.cj.jdbc.Driver
                username: root
                password: root
                url: jdbc:mysql://192.168.42.153:3306/voidme?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useSSL=false
            - xcdef:
                driver-class-name: com.mysql.cj.jdbc.Driver
                username: root
                password: root
                url: jdbc:mysql://192.168.42.153:3306/xcdef?characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&useSSL=false
      
      
      mybatis:
        #1.classpath:只会到你的classes路径中查找找文件。
        #2.classpath*:不仅会到classes路径,还包括jar文件中(classes路径)进行查找。
        mapper-locations: classpath*:/mapper/**/*Mapper.xml    # mapper映射文件位置
        type-aliases-package: com.**.entity    # 实体类所在的位置
        configuration:
          log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   #用于控制台打印sql语句
          map-underscore-to-camel-case: true #开启将带有下划线的表字段 映射为驼峰格式的实体类属性

      核心代码

      SpringBoot多数据源切换怎么实现

      DynamicDataSource

      这个类用于获取数据源的(核心)

      package com.dynamicdatadource.dynamic;
      
      import org.springframework.beans.factory.annotation.Value;
      import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
      
      public class DynamicDataSource extends AbstractRoutingDataSource {
      
          @Value("${spring.datasource.default-db-key}")
          private String defaultDbKey;
      
          @Override
          protected Object determineCurrentLookupKey() {
              String currentDb = DynamicDataSourceService.currentDb();
              if (currentDb == null) {
                  return defaultDbKey;
              }
              return currentDb;
          }
      }

      DynamicDataSourceService

      这个类是数据源切换工具,我们做了线程隔离了所以不用担心多线程数据源会混乱的问题

      package com.dynamicdatadource.dynamic;
      
      import com.application.ApplicationContextProvider;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.boot.jdbc.DataSourceBuilder;
      
      import javax.sql.DataSource;
      import java.util.HashMap;
      import java.util.Map;
      
      public class DynamicDataSourceService  {
          private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceService.class);
      
          private static final Map dataSources = new HashMap<>();
          private static final ThreadLocal dbKeys = ThreadLocal.withInitial(() -> null);
      
          /**
           * 动态添加一个数据源
           *
           * @param name       数据源的key
           * @param dataSource 数据源对象
           */
          public static void addDataSource(String name, DataSource dataSource) {
              DynamicDataSource dynamicDataSource = ApplicationContextProvider.getApplicationContext().getBean(DynamicDataSource.class);
              dataSources.put(name, dataSource);
              dynamicDataSource.setTargetDataSources(dataSources);
              dynamicDataSource.afterPropertiesSet();
              log.info("添加了数据源:{}",name);
          }
      
          /**
           * @param name   数据源的key
           * @param driverClassName  驱动
           * @param url     数据库连接地址
           * @param username   数据库账户
           * @param password   数据库密码
           */
          public static void addDataSource(String name, String driverClassName,String url,String username,String password) {
              DataSourceBuilder builder = DataSourceBuilder.create();
              builder.driverClassName(driverClassName);
              builder.username(username);
              builder.password(password);
              builder.url(url);
              addDataSource(name,builder.build());
              log.info("添加了数据源:{}",name);
          }
          /**
           * 切换数据源
           */
          public static void switchDb(String dbKey) {
              dbKeys.set(dbKey);
          }
      
          /**
           * 重置数据源(切换为默认的数据源)
           */
          public static void resetDb() {
              dbKeys.remove();
          }
      
          /**
           * 获取当前数据源的key
           */
          public static String currentDb() {
              return dbKeys.get();
          }
      }

      DynamicDataSourceConfig

      将数据源配置到springboot中和初始化Mybaitis配置

      package com.dynamicdatadource.dynamic;
      
      import lombok.Data;
      import org.apache.ibatis.logging.Log;
      import org.mybatis.spring.SqlSessionFactoryBean;
      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 org.springframework.transaction.PlatformTransactionManager;
      
      import java.io.IOException;
      import java.util.HashMap;
      import java.util.Map;
      
      @Configuration
      @ConfigurationProperties(prefix = "mybatis")
      @Data
      public class DynamicDataSourceConfig {
      
          private String mapperLocations;
          private String typeAliasesPackage;
          @Data
          public class MybatisConfiguration{
              private String logImpl;
              private boolean mapUnderscoreToCamelCase;
          }
          private  MybatisConfiguration configuration=new MybatisConfiguration();
      
      
          /**
           * 动态数据源
           */
          @Bean
          public DynamicDataSource dynamicDataSource() {
              DynamicDataSource dataSource = new DynamicDataSource();
              Map targetDataSources = new HashMap<>();
              dataSource.setTargetDataSources(targetDataSources);
              return dataSource;
          }
      
          /**
           * 会话工厂Mybaitis
           */
          @Bean
          public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException, ClassNotFoundException {
              org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
              configuration.setMapUnderscoreToCamelCase(this.configuration.isMapUnderscoreToCamelCase()); //开启驼峰命名
              configuration.setLogImpl((Class) Class.forName(this.configuration.getLogImpl())); //控制台打印sql日志
              SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
              sqlSessionFactoryBean.setDataSource(dynamicDataSource());
              sqlSessionFactoryBean.setConfiguration(configuration);
              PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
              sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
              sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
              return sqlSessionFactoryBean;
          }
      
          /**
           * 事务管理器
           */
          @Bean
          public PlatformTransactionManager transactionManager() {
              return new DataSourceTransactionManager(dynamicDataSource());
          }
      }

      加载YML数据库配置类

      package com.dynamicdatadource.config;
      
      import com.dynamicdatadource.dynamic.DynamicDataSourceService;
      import lombok.Data;
      import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
      import org.springframework.boot.context.properties.ConfigurationProperties;
      import org.springframework.boot.jdbc.DataSourceBuilder;
      import org.springframework.stereotype.Component;
      
      import javax.annotation.PostConstruct;
      import javax.sql.DataSource;
      import java.util.List;
      import java.util.Map;
      import java.util.Set;
      
      @Component
      @Data
      @ConfigurationProperties(prefix = "spring.datasource")
      public class YmlDataSourceProvider  {
      
          private List> multiDb;
      
          private DataSource buildDataSource(DataSourceProperties prop) {
              DataSourceBuilder builder = DataSourceBuilder.create();
              builder.driverClassName(prop.getDriverClassName());
              builder.username(prop.getUsername());
              builder.password(prop.getPassword());
              builder.url(prop.getUrl());
              return builder.build();
          }
      
          public void initDataSource() {
              multiDb.forEach(map -> {
                  Set keys = map.keySet();
                  keys.forEach(key -> {
                      DataSourceProperties properties = map.get(key);
                      DataSource dataSource = buildDataSource(properties);
                      DynamicDataSourceService.addDataSource(key, dataSource);
                  });
              });
          }
      
          //在构造函数之后执行
          @PostConstruct
          public void init() {
              initDataSource();
          }
      }

      aop切换

      package com.dynamicdatadource.aop;
      
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      
      @Target({ElementType.METHOD,ElementType.TYPE})//作用:方法和类
      @Retention(RetentionPolicy.RUNTIME)
      public @interface DynamicDataSourceAnno {
          String key() default "";
      }
      package com.dynamicdatadource.aop;
      import com.dynamicdatadource.dynamic.DynamicDataSourceService;
      import org.apache.commons.lang.StringUtils;
      import org.aspectj.lang.ProceedingJoinPoint;
      import org.aspectj.lang.annotation.Around;
      import org.aspectj.lang.annotation.Aspect;
      import org.aspectj.lang.annotation.Pointcut;
      import org.aspectj.lang.reflect.MethodSignature;
      import org.springframework.stereotype.Component;
      
      // 用于单独的请求或者类进行切换数据库
      @Aspect
      @Component
      public class DynamicDataSourceAspect {
          @Pointcut("@annotation(com.dynamicdatadource.aop.DynamicDataSourceAnno)")
          public void dynamicDataSourceAnno() {
          }
      
          @Around("dynamicDataSourceAnno()")
          public Object DynamicDataSourceAspectAroundAnno(ProceedingJoinPoint joinPoint) {
              Object object = null;
              try {
                  MethodSignature signature = (MethodSignature)joinPoint.getSignature();
                  DynamicDataSourceAnno dynamicDataSourceAnno  = signature.getMethod().getAnnotation(DynamicDataSourceAnno.class);
                  String key = dynamicDataSourceAnno.key();
                  if (StringUtils.isNotBlank(key)) {
                      //切换为指定数据库
                      DynamicDataSourceService.switchDb(key);
                  }
                  object = joinPoint.proceed();
              } catch (Throwable e) {
                  e.printStackTrace();
              }finally {
                  //还原为默认配置
                  DynamicDataSourceService.resetDb();
              }
              return object;
          }
          // 还可以扩展包路径切换
      }

      效果

      运行程序之后,就会将数据源加入到数据源列表中了

      SpringBoot多数据源切换怎么实现

      扩展

      MysqlDataSourceInitialize

      从数据库中将配置信息查询出来,然后动态添加到数据源列表中

      package com.dao.config;
      
      import com.dao.DatasourceDao;
      import com.dynamicdatadource.aop.DynamicDataSourceAnno;
      import com.dynamicdatadource.dynamic.DynamicDataSourceService;
      import com.entity.DataSourceEneity;
      import org.springframework.beans.factory.InitializingBean;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.ApplicationArguments;
      import org.springframework.boot.ApplicationRunner;
      import org.springframework.stereotype.Component;
      
      import javax.annotation.PostConstruct;
      import javax.sql.DataSource;
      import java.util.List;
      
      //从数据库中查询出全部的数据源,添加到数据源容器中
      
      /**
       * 表结构如下:
       *
       * CREATE TABLE `t_datasource` (
       *   `id` int(11) NOT NULL,
       *   `key` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '绑定的key,用于数据源的切换',
       *   `url` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '数据库连接地址',
       *   `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '数据库用户名',
       *   `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '数据库密码',
       *   `driverClassName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '数据库驱动',
       *   `type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '数据库类型:  mysql ,oracle,..',
       *   `state` int(2) NOT NULL COMMENT '是否可用: 1可用 ,2不可用',
       *   PRIMARY KEY (`id`),
       *   UNIQUE KEY `key` (`key`)
       * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
       *
       * 上表要放入到默认数据源中的数据库里才行
       */
      @Component
      public class MysqlDataSourceInitialize implements ApplicationRunner  {
      
          @Autowired
          private DatasourceDao datasourceDao;
      
          //项目启动后执行初始化数据源
          @Override
          public void run(ApplicationArguments args) throws Exception {
              try {
                  List dataSources = datasourceDao.getDataSources();
                  for (DataSourceEneity dataSource : dataSources) {
                      DynamicDataSourceService.addDataSource(dataSource.getKey(),dataSource.getDataSource());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

      DataSourceEneity实体类

      @Data
      public class DataSourceEneity {
          private int id;
          private String key;
          private String url;
          private String username;
          private String password;
          private String driverClassName;
          private String type;
          private int state;
      
          public  DataSource getDataSource() {
              DataSourceBuilder builder = DataSourceBuilder.create();
              builder.driverClassName(driverClassName);
              builder.username(username);
              builder.password(password);
              builder.url(url);
              return  builder.build();
          }
      }
      本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
      作者最新文章
      编程开发
      相关文章 更多
      精品专题 更多
      装机必备

      正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

      Windows

      正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

      PDF教程

      正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

      macOS软件

      正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

      IOS软件

      正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

      AI

      正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

      Mac软件 更多
      讯飞智作 网页版
      讯飞智作 网页版

      讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

      火山引擎 网页版
      火山引擎 网页版

      火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

      Aperty macOS版
      Aperty macOS版

      Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

      立刻MV 网页版
      立刻MV 网页版

      立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

      蛙蛙写作 网页版
      蛙蛙写作 网页版

      蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

      超级简历WonderCV 网页版
      超级简历WonderCV 网页版

      超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

      音述AI 网页版
      音述AI 网页版

      音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

      AionClaw macOS版
      AionClaw macOS版

      AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

      Loomy macOS版
      Loomy macOS版

      Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

      AirBuddy 3 macOS版
      AirBuddy 3 macOS版

      AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

      AirServer macOS版
      AirServer macOS版

      AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

      AnyDesk macOS版
      AnyDesk macOS版

      AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

      WINDOWS 更多
      讯飞智作 网页版
      讯飞智作 网页版

      讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

      火山引擎 网页版
      火山引擎 网页版

      火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

      PixTV 网页版
      PixTV 网页版

      PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。

      讯飞绘文 网页版
      讯飞绘文 网页版

      讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

      Maya(Autodesk Maya) Windows版
      Maya(Autodesk Maya) Windows版

      Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

      Aperty Windows版
      Aperty Windows版

      Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

      立刻MV 网页版
      立刻MV 网页版

      立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

      蛙蛙写作 网页版
      蛙蛙写作 网页版

      蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

      超级简历WonderCV 网页版
      超级简历WonderCV 网页版

      超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

      音述AI 网页版
      音述AI 网页版

      音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

      AionClaw Windows版
      AionClaw Windows版

      AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

      Loomy Windows版
      Loomy Windows版

      Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。