手把手实现项目中自定义动态数据源?

news2024/9/28 1:24:44

手把手实现项目中自定义动态数据源?

  • 第一步:创建项目,添加POM依赖
  • 第二步:添加application.yml配置文件
  • 第三步:自定义注解指定使用哪个数据源
  • 第四步:创建DynamicDataSourceContextHolder工具类,存储当前线程所使用的数据源名称
  • 第五步:定义DataSourceAspect切面类,拦截类或者方法上的注解
  • 第六步:DruidProperties类属性注入
  • 第七步:LoadDataSource加载数据源
  • 第八步:DynamicDataSource 继承 AbstractRoutingDataSource 自动返回数据源名称,并设置数据源
  • 第九步:数据库
  • 第十步:测试

使用一个小例子演示一下自定义动态数据源的步骤。

第一步:创建项目,添加POM依赖

	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
  
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.31</version>
            <scope>runtime</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

第二步:添加application.yml配置文件

# 数据源配置
spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        ds:
            # 主库数据源
            master:
                url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
                username: root
                password: 123456
            # 从库数据源
            slave:
                url: jdbc:mysql://localhost:3306/test_slave?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
                username: root
                password: 123456
        # 初始连接数
        initialSize: 5
        # 最小连接池数量
        minIdle: 10
        # 最大连接池数量
        maxActive: 20
        # 配置获取连接等待超时的时间
        maxWait: 60000
        # 配置连接超时时间
        connectTimeout: 30000
        # 配置网络超时时间
        socketTimeout: 60000
        # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        timeBetweenEvictionRunsMillis: 60000
        # 配置一个连接在池中最小生存的时间,单位是毫秒
        minEvictableIdleTimeMillis: 300000
        # 配置一个连接在池中最大生存的时间,单位是毫秒
        maxEvictableIdleTimeMillis: 900000
        # 配置检测连接是否有效
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        webStatFilter:
            enabled: true
        statViewServlet:
            enabled: true
            # 设置白名单,不填则允许所有访问
            allow:
            url-pattern: /druid/*
            # 控制台管理用户名和密码
            login-username: valiant
            login-password: 123456
        filter:
            stat:
                enabled: true
                # 慢SQL记录
                log-slow-sql: true
                slow-sql-millis: 1000
                merge-sql: true
            wall:
                config:
                    multi-statement-allow: true

第三步:自定义注解指定使用哪个数据源

/**
 * 自定义注解,可以加在 service 类或者方法上,value指定使用哪个数据源
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface DataSource {
    String value() default DSType.DEFAULT_DS_NAME;
}
//默认类型,后边也可以用到
public interface DSType {
    String DEFAULT_DS_NAME = "master";
}

第四步:创建DynamicDataSourceContextHolder工具类,存储当前线程所使用的数据源名称

/**
 * 存储当前线程所使用的数据源名称
 */
public class DynamicDataSourceContextHolder {

    private static ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();

    public static void setDSType(String dsType){
        CONTEXT_HOLDER.set(dsType);
    }

    public static String getDSType(){
        return CONTEXT_HOLDER.get();
    }

    public static void delDSType(){
        CONTEXT_HOLDER.remove();
    }
}

第五步:定义DataSourceAspect切面类,拦截类或者方法上的注解

@Component
@Aspect
public class DataSourceAspect {

    /**
     * @annotation(com.kun.dd.annotation.DataSource) 拦截方法上的DataSource注解
     * @within(com.kun.dd.annotation.DataSource) 如果类上标有注解,就将类中的方法拦截
     */
    @Pointcut("@annotation(com.kun.dd.annotation.DataSource) || @within(com.kun.dd.annotation.DataSource)")
    public void pc(){};

    @Around("pc()")
    public Object around(ProceedingJoinPoint pjp){
        //优先获取方法上的注解,没有在获取类上的
        DataSource dataSource = getDataSource(pjp);
        if (dataSource != null){
            //获取数据源名称
            String value = dataSource.value();
            DynamicDataSourceContextHolder.setDSType(value);
        }

        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {
            DynamicDataSourceContextHolder.delDSType();
        }
        return null;
    }

    private DataSource getDataSource(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        //查找方法上的注解
        DataSource annotation = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (annotation != null){
            return annotation;
        }
        //方法上没有去类上找
        return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
    }
}

第六步:DruidProperties类属性注入

/**
 * 属性注入
 */
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperties {

    private String type;
    private String driverClassName;
    private Map<String,Map<String,String>> ds;
    private Integer initialSize;
    private Integer minIdle;
    private Integer maxActive;
    private Integer maxWait;
    //其他的属性暂时省略......

    /**
     * 传入的DruidDataSource只包含三个核心属性,url,name,password
     * 其他的公共属性在这个类里边设置
     * @param druidDataSource
     * @return
     */
    public DataSource dataSource(DruidDataSource druidDataSource){
        druidDataSource.setInitialSize(initialSize);
        druidDataSource.setMaxActive(maxActive);
        druidDataSource.setMinIdle(minIdle);
        druidDataSource.setMaxWait(maxWait);

        return druidDataSource;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public Map<String, Map<String, String>> getDs() {
        return ds;
    }

    public void setDs(Map<String, Map<String, String>> ds) {
        this.ds = ds;
    }

    public Integer getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(Integer initialSize) {
        this.initialSize = initialSize;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }
}

第七步:LoadDataSource加载数据源

@Component
@EnableConfigurationProperties(DruidProperties.class)
public class LoadDataSource {

    @Autowired
    DruidProperties druidProperties;

    public Map<String, DataSource> loadAllDataSource(){
        Map<String,DataSource> map = new HashMap<>();
        Map<String, Map<String, String>> ds = druidProperties.getDs();

        try {
            //创建所有的数据源
            Set<String> keySet = ds.keySet();
            for (String key : keySet){
                map.put(key, druidProperties.dataSource((DruidDataSource) DruidDataSourceFactory.createDataSource(ds.get(key))));
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

}

第八步:DynamicDataSource 继承 AbstractRoutingDataSource 自动返回数据源名称,并设置数据源

@Component
public class DynamicDataSource extends AbstractRoutingDataSource {

    public DynamicDataSource(LoadDataSource loadDataSource){
        //1.设置所有数据源
        Map<String, DataSource> allDS = loadDataSource.loadAllDataSource();
        super.setTargetDataSources(new HashMap<>(allDS));
        //2.设置默认数据源(有些没有标注解的方法使用)
        super.setDefaultTargetDataSource(allDS.get(DSType.DEFAULT_DS_NAME));
        //3
        super.afterPropertiesSet();
    }

    /**
     * 系统需要获取数据源时,会自动调用该方法返回数据源名称
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDSType();
    }
}

第九步:数据库

  • 主从数据库都有一个user表(id,name,age),主表name后带 _m,从表name后带 _s。
    在这里插入图片描述
//实体类
public class User {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

第十步:测试

//创建mapper接口
@Mapper
public interface UserMapper {

    @Select("select * from user")
    List<User> getAllUsers();
}
//创建service
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public List<User> getAllUsers(){
        return userMapper.getAllUsers();
    }
}
//单元测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class DynamicSourceApplicationTests {

    @Autowired
    UserService userService;

    @Test
    public void contextLoads() {
        List<User> allUsers = userService.getAllUsers();
        for (User user : allUsers){
            System.out.println(user);
        }
    }
}

没有加注解时:
在这里插入图片描述
给方法或者类上加注解时:
在这里插入图片描述
测试完成:源码地址点击跳转

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/504415.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

LeetCode:347. 前 K 个高频元素

&#x1f34e;道阻且长&#xff0c;行则将至。&#x1f353; &#x1f33b;算法&#xff0c;不如说它是一种思考方式&#x1f340; 算法专栏&#xff1a; &#x1f449;&#x1f3fb;123 题解目录 一、&#x1f331;[347. 前 K 个高频元素](https://leetcode.cn/problems/bina…

安全防线再升级 | 中睿天下全流量安全分析系统重磅回归

随着信息化的加速&#xff0c;企业网络日趋完善。企业数字化的加速&#xff0c;让越来越多的关键业务运行在计算机网络基础之上&#xff0c;越来越多的重要信息通过网络传送&#xff0c;企业网络面临日益严重的安全威胁&#xff0c;这些安全威胁以窃取信息和收集情报为主&#…

基于docker安装MySQL

为了更好的管理&#xff0c;打算把MySQL、redis等服务放在虚拟机中统一部署&#xff0c;这样不会因为这些服务的问题影响到系统本身。前段时间正好在看docker相关的内容&#xff0c;打算在虚拟机中通过docker来使用MySQL等服务。 这次先记录安装MySQL的过程。 docker安装 首先…

超越 Nginx!号称下一代 Web 服务器,用起来够优雅!

Nginx是一款非常流行的Web服务器&#xff0c;在Github上已有16KStar&#xff0c;我们经常用它来做静态资源托管或反向代理。最近发现了一款全新的Web服务器Caddy&#xff0c;Star数超越Nginx&#xff0c;标星38KStar。试用了一下Caddy&#xff0c;发现它使用起来比Nginx优雅多了…

掌握这五个核心步骤,让你的方案完美无缺

写策划方案怎么来写&#xff0c;可能会是刚入行策划人的难点&#xff0c;策划方案其实就是一份营销计划&#xff0c;一份完整的策划能让策划人看清自己、认清竞争对手&#xff0c;形成对市场的整体认知。 一般大的营销策划方案里面会用到STP、SWOT和4P等模型&#xff0c;模型本…

【Java多线程编程】创建线程的基本方式

大家好&#xff0c;我是一只爱打拳的程序猿。今天给大家带来的内容是 Java 创建线程的基本方式。 多线程的基本创建方式: 继承Thread类实现Runnable接口匿名内部类使用lambda表达式 目录 1. 继承Thread类 1.1 Thread类启动线程 2. 实现Runnable接口 2.1 创建Thread类实例…

while和until的使用方法(还有一些小实验:计算器、猜价格游戏、购物)

while和until的使用方法 一、while用法二、Until循环语句三、猜价格小实验四、计算器实验六、购物实验 一、while用法 for循环语句非常适用于列表对象无规律&#xff0c;且列表来源以固定&#xff08;如某个列表文件&#xff09;的场合。而对于要求控制循环次数&#xff0c;操…

C++学习day--06 向计算机输入数据

1、输入 当缓冲区为空时&#xff0c;程序才会暂停&#xff0c;让用户输入数据。 输入回车后&#xff0c;数据全部送到输入缓冲区。 #include <iostream> #include <Windows.h> int main( void ){ char girlType; int salary; float height; std::cout &l…

记录--极致舒适的Vue页面保活方案

这里给大家分享我在网上总结出来的一些知识&#xff0c;希望对大家有所帮助 为了让页面保活更加稳定&#xff0c;你们是怎么做的&#xff1f; 我用一行配置实现了 Vue页面保活是指在用户离开当前页面后&#xff0c;可以在返回时恢复上一次浏览页面的状态。这种技术可以让用户享…

shell脚本4函数

文章目录 shell脚本函数1 函数概述2 定义2.1 形式2.2 使用原则2.3 函数传参2.4 函数变量的作用范围 3 递归3.1 阶乘 4 函数库5 实验5.1 阶乘5.2 递归目录5.3 调用函数库 shell脚本函数 1 函数概述 1、将命令序列按格式写在一起 2、可方便重复使用命令序列 使用函数可以避免代码…

FS4067升压充电8.4V锂电池充电IC电流3A

FS4067升压型5V升压充电8.4V两串锂电池充电IC&#xff0c;工作电压范围于 2.7V 到 6.5V 的 PFM 升压型两节锂电池充电控制集成电路。 FS4067采用恒流和恒压模式对电池进行充电管理&#xff0c;内部集成有基准电压源&#xff0c; 电感电流检测单元&#xff0c;电池电压检测电路和…

【原创】强烈推荐三个可视化模块,绘制的图表真的很酷炫!!

Matplotlib是Python编程语言中最受欢迎的绘图库之一。它提供了一套面向对象的API&#xff0c;可将图表嵌入到使用通用GUI工具包&#xff08;如Tkinter、wxPython、Qt或GTK&#xff09;的应用程序中。Matplotlib还常用于创建静态、动画和交互式的Python数据可视化。它能够绘制各…

【Unity】在Unity下使用websocket的一些经验

首先&#xff0c;先上大家都知道的简介&#xff0c;这一版是我认为比较清晰的。。。虽然在度娘的教导和知乎的教导下&#xff0c;总算认识了websocket&#xff0c;但这个过程比较艰辛&#xff0c;给大家发出来看一下&#xff1a; --------------------------------------------…

精准测试之过程与实践 | 京东云技术团队

作者&#xff1a;京东工业 宛煜昕 一、怎样的技术 •百度百科&#xff1a; 精准测试是一套计算机测试辅助分析系统。 精准测试的核心组件包含的软件测试示波器、用例和代码的双向追溯、智能回归测试用例选取、覆盖率分析、缺陷定位、测试用例聚类分析、测试用例自动生成系统…

苹果(ios)家庭APP广告推送,照片,相册,日历消息推送,【iMessage苹果推】,【苹果家庭推群发】,【imessage相册推送】

解决方案 若是你完全担任苹果的这个默许功效&#xff0c;那就不必要去编削任何代码。 如果&#xff0c;你原本就比较细心&#xff0c;曾经配置了modalPresentationStyle的值&#xff0c;那你也不会有这个影响。 对于想要找回本来默认交互的同学&#xff0c;直接设置以下便可&am…

携手共赢 HashData亮相华为合作伙伴大会

5月8日-9日&#xff0c;以“因聚而生 众志有为”为主题的“华为中国合作伙伴大会2023”在深圳国际会展中心举办。 HashData作为国内云原生数据仓库的代表企业&#xff0c;也是华为重要的生态合作伙伴。在本次大会上&#xff0c;HashData展示了云数仓领域最新前沿技术以及联合…

Java经典笔试题—day04

Java经典笔试题—day04 &#x1f50e;选择题&#x1f50e;编程题&#x1f95d;计算糖果&#x1f95d;进制转换 &#x1f50e;结尾 &#x1f50e;选择题 (1)下列与队列结构有关联的是&#xff08;&#xff09; A. 函数的递归调用 B. 数组元素的引用 C. 多重循环的执行 D. 先到…

Windows系统运行速度优化(系统内存扩充)!

之前有几篇文章&#xff0c;讲述了一些关于提升Windows系统运行速度的方法。链接如下&#xff1a; 如何让Windows系统10秒开机&#xff1f; 电脑运行卡顿怎么办&#xff1f;一招让Windows系统运行流畅 Windows系统重新安装后必须要做的优化 这里还有一个Windows系统的优化方法…

技术领先、“忠”于业务,用友走出多维数据库的价值之路

本文转自科技商业 作者 于洪涛 对于当今的企业而言&#xff0c;精细化管理&#xff0c;已经成为发展之源&#xff0c;甚至是生存之本。 尤其是随着数字化和智能化转型的推进&#xff0c;在企业经营管理过程中&#xff0c;数据正在日益发挥更为关键的要素作用。 相比过去&…

【Linux】Shell脚本之函数的操作+实战详解(建议收藏⭐)

&#x1f341;博主简介 &#x1f3c5;云计算领域优质创作者   &#x1f3c5;华为云开发者社区专家博主   &#x1f3c5;阿里云开发者社区专家博主 &#x1f48a;交流社区&#xff1a;运维交流社区 欢迎大家的加入&#xff01; 文章目录 shell脚本函数设置函数的意义函数的基…