双数据源 - 方式一

个人博客地址
注解+aop

先把个人的结论写前面

  • 通过aop + 注解的形式在切面切换数据源实现
    • 优势: 对本身的代码分层没有任何变化.即两个数据源对应的entity/repository不变
    • 劣势: aop切父类方法会失效;即:如果使用通用mapper则会导致父类方法没切到
  • 通过不同数据源扫描不同的包实现
    • 优势: 只关心实体类对应包即可,不需要额外增加注解
    • 劣势:有一定的侵入; 比如原本dao在repository包下,现在需要再建一个;比如原先的迁移到dao.primary包下; 第二数据源放在dao.second包下

第一种方式: aop+注解

流程效果 : 调用repository层方法前;通过切面切换数据源; 直接撸代码

step1 增加注解:

因为一个repository类不应该同时对应两个数据库; 应该注解指定定义类使用即可

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE})
public @interface DataSourceType {

    DBTypeEnum value() default DBTypeEnum.PRIMARY;
}

同时定义下两种不同数据源的枚举

@Getter
public enum DBTypeEnum {
    PRIMARY("primaryDb"),
    LOG("logDb"),;
    private String dbName;
    DBTypeEnum(String dbName) {
        this.dbName = dbName;
    }
}

step2 动态数据源

spring.datasource.druid.url=jdbc:mysql://127.0.0.1:3306/sharding_0?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.log.url=jdbc:mysql://127.0.0.1:3306/sharding_1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
spring.datasource.log.username=root
spring.datasource.log.password=root
spring.datasource.log.driver-class-name=com.mysql.cj.jdbc.Driver

使用时

在mapper类上加入指定的注解

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容