多数据源

简介: 快速开发实战

什么时候需要多数据源切换

①、项目中存储的数据量很大,一个服务器扛不住,需要将一部分数据存储在另外一个服务器里,然而我们还要每天去访问这些存储的数据。
②、项目与其他项目对接,需要连接另外一个项目的数据库(这里可能有人会提议使用API,但这是相对于第三方公司,人家不会把数据库信息暴露给你的,所以才提供的api。)

实现多数据源切换实现(springboot+aop)

添加相关pom

         <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- alibaba durid 数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

配置yml相关数据源

假如我们有两个数据库 readDate,wirteDate

spring:
  datasource:
    readDate:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://XXXX:XXX/readDate?useUnicode=true&characterEncoding=utf-8
      username: xxx
      password: xxxx
      type: com.alibaba.druid.pool.DruidDataSource

    wirteDate:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://XXXX:XXX/wirteDate?useUnicode=true&characterEncoding=utf-8
      username: xxx
      password: xxxx
      type: com.alibaba.druid.pool.DruidDataSource

创建数据源枚举

@AllArgsConstructor
@Getter
public enum DataSourceEnum {

    DEFAULT("wirteDate"),
    WRITEDATE("wirteDate"),
    READDATE("readDate");
    private String name;
}

创建多数据源自定义注解

/**
 * 数据源
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface DataSource {

    //枚举
    DataSourceEnum value();
}

创建DataSourceHolder用来存储数据源

public class DataSourceHolder {

    private static final ThreadLocal<String> DS_HOLDER = new ThreadLocal<>();

    public static void setDataSource(DataSourceEnum dataSource) {

        DS_HOLDER.set(dataSource.getName());
    }

    public static String getDataSource() {

        return DS_HOLDER.get();
    }

    public static void clearDataSource() {

        DS_HOLDER.remove();
    }
}

创建DynamicDataSource

继承AbstractRoutingDataSource用来切换数据源

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {

        //基于aop切换数据源
        System.out.println("dynamic datasource 切换数据源" + DataSourceHolder.getDataSource());
        return DataSourceHolder.getDataSource();
    }
}

创建数据源,连接数据库db的config

@Configuration
public class DataSourceConfig {

    //连接数据库writeDate
    @Bean("writeDate")
    @ConfigurationProperties("spring.datasource.writeDate")
    public DataSource writeDateDb() {

        return new DruidDataSource();
    }

    //连接数据库readDate
    @Bean("readDate")
    @ConfigurationProperties("spring.datasource.readDate")
    public DataSource readDateDb() {

        return new DruidDataSource();
    }

    @Bean("dynamicDataSource")
    @Primary
    public DataSource dynamicDataSource() {
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setDefaultTargetDataSource(writeDateDb());
        Map<Object, Object> dataSourceMap = new HashMap<>(2);
        dataSourceMap.put(DataSourceEnum.TEST1.getName(), writeDateDb());
        dataSourceMap.put(DataSourceEnum.TEST2.getName(), readDateDb());
        dataSource.setTargetDataSources(dataSourceMap);
        return dataSource                                                                                                               ;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}

创建基于自定义注解的切面


@Aspect
@Component
@Order(1)
public class DataSourceAsepct {

    //加载数据源
    @Pointcut("@annotation(com.xxxx.config.DataSource)")
    public void pointCut(){ }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Object target = joinPoint.getTarget();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        DataSourceEnum dataSource = DataSourceEnum.DEFAULT;
        try {
            Method method = target.getClass().getMethod(signature.getName(), signature.getParameterTypes());
            if (method.isAnnotationPresent(DataSource.class)) {
                DataSource annotation = method.getAnnotation(DataSource.class);
                dataSource = annotation.value();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        //实现aop切换数据源
        System.out.println("aop切换数据源:" + dataSource.getName());
        DataSourceHolder.setDataSource(dataSource);
    }

    @After("pointCut()")
    public void after() {
        DataSourceHolder.clearDataSource();
    }
}

启动类上记得加@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

最后使用自定义注解

对数据库的操作这里不做描述,认为都写好了mapper层

@Service
public class TestServiceImpl {

  
    @Autowired
    private WriteMapper mapper1;
      @Autowired
    private ReadMapper     mapper2;

    @Override
    public void  addUser(User user) {

        // 不指定,则默认使用数据源1
        return mapper1.save(user);
    }

    // 覆盖类上指定的数据源2
    @DataSource(DataSourceEnum.READDATE)
    @Override
    public List<Map<String, User>> findUser() {

        return mapper2.findAll();
    }

    /**
     * 如果切面不加@Order,添加Transactional注解会导致切换数据源失效
     */
    @Transactional
    @DataSource(DataSourceEnum.WRITEDATE)
    @Override
    public void insert(User user) {
        mapper1.insert(user);
    }
}

结束!!!

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
Linux 虚拟化
Linux命令(35)之shutdown
Linux命令(35)之shutdown
1557 1
|
存储 Kubernetes 关系型数据库
在Kubernetes中,helm是什么?如何使用?
【4月更文挑战第9天】在Kubernetes中,helm是什么?如何使用?
1586 5
|
数据采集 搜索推荐 小程序
全开源、私有化部署!轻量级用户行为分析系统-ClkLog
随着数据安全要求日益严格,越来越多企业、项目方在选择埋点系统时,开始倾向于私有化部署和自主掌控数据。
1380 57
|
Kubernetes 容器
k8s ingress获取真实IP地址配置
背景 业务架构:Client->WAF->LB->ECS->容器问题:在容器中获取不到真实的客户端公网IP 抓包分析 在ECS上的抓包分析,看到WAF已经将 真实客户端地址放到了 x-Forwarded-For 的字段中传给了ECS ![image](https://yqfile.
18568 0
|
人工智能 编解码 API
通义万相AIGC技术测评报告
**摘要:** 通义万相是阿里云的AI绘画模型,提供清晰的部署指南和易用的API,适合新手。资源部署耗时约10分钟,API响应快,支持多种风格图片生成,适用于广告、媒体等领域。产品性价比高,功能包括文本到图像转换等,但仍有改进空间,如增加服装纹理选项、互动功能和更多API接口。建议完善功能、加强推广和降低成本以吸引更多用户。[链接](https://developer.aliyun.com/topic/tongyi-wanxiang?spm=a2c6h.27063436.J_6978680750.5.3a774f461hv8qD)
1924 6
|
机器学习/深度学习 算法 物联网
LoRA及其变体概述:LoRA, DoRA, AdaLoRA, Delta-LoRA
LoRA可以说是针对特定任务高效训练大型语言模型的重大突破。它被广泛应用于许多应用中。在本文中,我们将解释LoRA本身的基本概念,然后介绍一些以不同的方式改进LoRA的功能的变体,包括LoRA+、VeRA、LoRA- fa、LoRA-drop、AdaLoRA、DoRA和Delta-LoRA。
2152 2
|
druid Java Maven
|
Kubernetes 容器
基于Ubuntu-22.04安装K8s-v1.28.2实验(三)数据卷挂载NFS(网络文件系统)
基于Ubuntu-22.04安装K8s-v1.28.2实验(三)数据卷挂载NFS(网络文件系统)
895 0
|
Java Spring
SpringBoot项目中整合MinIO
SpringBoot项目中整合MinIO。
1085 5
|
存储 JSON Java
spring boot3登录开发-1(整合jwt)
spring boot3登录开发-1(整合jwt)
1340 1

热门文章

最新文章