springboot实现多数据源配置(Druid/Hikari)

2023-11-03 13:50

本文主要是介绍springboot实现多数据源配置(Druid/Hikari),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用springboot+mybatis-plus+(Druid/Hikari)实现多数据源配置

操作步骤:
  1. 引入相应的maven坐标
  2. 编写mybatis配置,集成mybatis或mybatis-plus(如果已集成可跳过)
  3. 编写数据源配置类
  4. 编写注解,并通过aop进行增强(编写数据源切换代码)
  5. 类或方法中使用注解,对数据源进行切换

第一步:引入需要相应maven坐标

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- aop注解实现aspectjweaver依赖 --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.6</version></dependency><!-- mysql-plus 依赖 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.0</version></dependency><!-- Mysql驱动包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--阿里数据库连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.14</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>

第二步:编写mybatis-plus配置集成

server:port: 8000spring:datasource:driver-class-name: com.mysql.cj.jdbc.Drivermaster:url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=trueusername: rootpassword: 123456slaver:# 从数据源开关/默认关闭enabled: falseurl: jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=trueusername: rootpassword: 123456druid:# 初始连接数initial-size: 5# 最小连接池数量min-idle: 10# 最大连接池数量max-active: 20# 获取连接等待超时时间max-wait: 60000
mybatis-plus:mapper-locations: classpath*:mapper/*Mapper.xmllogging:level:com.example.demo: debug
以下是集成mp相关的代码,不需要可直接跳过!!!(以user表为例)

userMapper

package com.example.demo.datesource.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.datesource.domain.User;import java.util.List;public interface UserService extends IService<User> {List<User> getUserList();List<User> getUserListByXml();List<User> testSlave();
}

userMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.datesource.mapper.UserMapper"><select id="getUserListByXml" resultType="com.example.demo.datesource.domain.User">select * from user</select>
</mapper>

userService

package com.example.demo.datesource.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.datesource.domain.User;import java.util.List;public interface UserService extends IService<User> {List<User> getUserList();List<User> getUserListByXml();List<User> testSlave();
}

userServiceImpl

package com.example.demo.datesource.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.datesource.annotation.UseDataSource;
import com.example.demo.datesource.domain.User;
import com.example.demo.datesource.enums.DataSourceType;
import com.example.demo.datesource.mapper.UserMapper;
import com.example.demo.datesource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic List<User> getUserList() {return list();}@Overridepublic List<User> getUserListByXml(){return userMapper.getUserListByXml();}@Overridepublic List<User> testSlave() {return list();}
}

User

package com.example.demo.datesource.domain;import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;@Data
@TableName("user")
public class User {@TableIdprivate Long id;private String name;private String sex;private int age;
}
mybatis-plus 集成完毕!

第三步:编写数据源的配置类(例:Druid、Hikari)

一、@ConfigurationProperties要和配置文件中的配置对应上
(1)Druid:
package com.example.demo.datesource.config;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.example.demo.datesource.config.properties.DruidPropertiesConfig;
import com.example.demo.datesource.datasource.DynamicDataSource;
import com.example.demo.datesource.enums.DataSourceType;
import com.example.demo.datesource.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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 javax.sql.DataSource;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map;@Configuration
public class DruidConfig {@Bean@ConfigurationProperties("spring.datasource.master")public DataSource masterDataSource(DruidPropertiesConfig propertiesConfig){DruidDataSource dataSource = DruidDataSourceBuilder.create().build();return propertiesConfig.setDataSourceProperties(dataSource);}@Bean@ConfigurationProperties("spring.datasource.slaver")@ConditionalOnProperty(prefix = "spring.datasource.slaver", name = "enabled", havingValue = "true")public DataSource slaverDataSource(DruidPropertiesConfig propertiesConfig){DruidDataSource dataSource = DruidDataSourceBuilder.create().build();return propertiesConfig.setDataSourceProperties(dataSource);}@Bean@Primarypublic DynamicDataSource dataSource(DataSource masterDataSource){Map<Object,Object> targetDataSource = new HashMap<>();targetDataSource.put(DataSourceType.MASTER.name(),masterDataSource);setDataSource(targetDataSource,DataSourceType.SLAVE.name(),"slaverDataSource");return new DynamicDataSource(masterDataSource,targetDataSource);}public void setDataSource(Map<Object,Object> targetDataSource,String sourceName,String beanName){try {DataSource dataSource = SpringUtils.getBean(beanName);targetDataSource.put(sourceName,dataSource);}catch (Exception e){}}}

增加DruidPropertiesConfig类,用于给数据源配置上配置文件对应的属性

package com.example.demo.datesource.config.properties;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;@Configuration
public class DruidPropertiesConfig {@Value("${spring.datasource.druid.initial-size}")private int initialSize;@Value("${spring.datasource.druid.min-idle}")private int minIdle;@Value("${spring.datasource.druid.max-active}")private int maxActive;@Value("${spring.datasource.druid.max-wait}")private int maxWait;public DruidDataSource setDataSourceProperties(DruidDataSource dataSource){dataSource.setInitialSize(this.initialSize);dataSource.setMinIdle(this.minIdle);dataSource.setMaxActive(this.maxActive);dataSource.setMaxWait(this.maxWait);return dataSource;}}
(2)Hikari:配置上基本和druid相同,只需把配置类改为如下且配置文件的“url”改为“jdbc-url”即可

在这里插入图片描述
在这里插入图片描述

二、增加SpringUtils类,用于读取spring中的bean
package com.example.demo.datesource.utils;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;@Component
public class SpringUtils implements BeanFactoryPostProcessor {private static ConfigurableListableBeanFactory beanFactory;@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {SpringUtils.beanFactory = configurableListableBeanFactory;}public static <T> T getBean(String name){return (T) beanFactory.getBean(name);}}
三、添加DynamicDataSource类

(1)此类是用来配置动态数据源的关键。该类继承spring的抽象类AbstractRoutingDataSource,通过这个类可以实现动态数据源切换。其中维护着默认数据源(defaultTargetDataSource)和数据源列表(targetDataSources),通过afterPropertiesSet()方法对数据源列表进行解析以及设置数据源。
程序每次对数据库发起连接时,都会访问到AbstractRoutingDataSource的getConnection()方法,此方法会调用determineCurrentLookupKey的相应实现,此处实现为获取线程变量。

package com.example.demo.datesource.datasource;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import javax.sql.DataSource;
import java.util.Map;public class DynamicDataSource extends AbstractRoutingDataSource {public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources){super.setDefaultTargetDataSource(defaultTargetDataSource);super.setTargetDataSources(targetDataSources);super.afterPropertiesSet();}@Overrideprotected Object determineCurrentLookupKey() {return DynamicDataSourceContextHolder.getDataSourceType();}
}

(2)添加DynamicDataSourceContextHolder类,此类用于切换数据源,根据ThreadLocal做多线程数据隔离,每一次切换都能保证不影响其他线程的正常运行

package com.example.demo.datesource.datasource;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class DynamicDataSourceContextHolder {public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);private static final ThreadLocal<String> CONTEXT_HOLDER =  new ThreadLocal<>();/*** 设置数据源的变量*/public static void setDataSourceType(String dsType){log.info("切换到{}数据源",dsType);CONTEXT_HOLDER.set(dsType);}/*** 获得数据源的变量*/public static String getDataSourceType(){return CONTEXT_HOLDER.get();}/*** 清空数据源变量,此方法可调动gc对线程进行清除*/public static void clearDataSourceType(){CONTEXT_HOLDER.remove();}}

AbstractRoutingDataSource切换线程变量来切换数据源源码。
此处就是获取之前在DynamicDataSourceContextHolder中set到线程中的数据源名,通过数据源名获取维护的数据源列表中对应的数据源

在这里插入图片描述

第四步:使用

大致思路:定义一个切换数据源注解,通过注解aop的形式对数据源进行切换,在类或方法中使用注解,设置对应的数据源名称以此来达到数据源切换

一、定义一个切换数据源注解
package com.example.demo.datesource.annotation;import com.example.demo.datesource.enums.DataSourceType;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 UseDataSource {public DataSourceType dataSource() default DataSourceType.MASTER;}
二、编写aop代码

@within:此注解可以作用于类中的所有方法,如果@UseDataSource放到类上,此类下的所有的方法都会被当做切点拦截
@Order(1):提升组件注册到spring中的优先级
point.proceed():原来执行的程序,也就是原请求,想要做环绕增强就再这周围写就可以了

package com.example.demo.datesource.aspectj;import com.example.demo.datesource.annotation.UseDataSource;
import com.example.demo.datesource.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;import javax.sql.DataSource;
import java.util.Objects;@Aspect
@Order(1)
@Component
public class DataSourceAspect {@Pointcut("@annotation(com.example.demo.datesource.annotation.UseDataSource) || @within(com.example.demo.datesource.annotation.UseDataSource)")public void pointCut(){}@Around("pointCut()")public Object around(ProceedingJoinPoint point) throws Throwable{UseDataSource useDataSource = getDataSource(point);if(Objects.nonNull(useDataSource)){DynamicDataSourceContextHolder.setDataSourceType(useDataSource.dataSource().name());}try {return point.proceed();}finally {//清空threadlocalMap的entry。避免内存泄漏DynamicDataSourceContextHolder.clearDataSourceType();}}public UseDataSource getDataSource(ProceedingJoinPoint point){MethodSignature signature = (MethodSignature) point.getSignature();UseDataSource annotation = AnnotationUtils.findAnnotation(signature.getMethod(), UseDataSource.class);if(Objects.nonNull(annotation)){return annotation;}return AnnotationUtils.findAnnotation(signature.getDeclaringType(),UseDataSource.class);}}
三、编写注解到类或方法上

在这里插入图片描述

运行结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

至此,数据源切换成功!!!

另外,如果需要增加新的数据源需要的操作:
1、启动配置文件中增加新的数据源参数
2、数据源配置类中,新增配置源bean,并且把数据源set到targetDataSource中
3、DataSourceType枚举类中,添加新数据源的枚举
如图所示:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

这篇关于springboot实现多数据源配置(Druid/Hikari)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/338613

相关文章

Java Stream流与使用操作指南

《JavaStream流与使用操作指南》Stream不是数据结构,而是一种高级的数据处理工具,允许你以声明式的方式处理数据集合,类似于SQL语句操作数据库,本文给大家介绍JavaStream流与使用... 目录一、什么是stream流二、创建stream流1.单列集合创建stream流2.双列集合创建str

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很