苞米豆多数据源配置,跨数据源业务操作注意事项

参考链接地址:https://dynamic-datasource.com/guide/tx/Local.html#注意事项

苞米豆多数据配置在pom.xml使用


    com.alibaba
    druid-spring-boot-starter
    1.1.22

注意:需要使用1.1.22以上版本,具体原因参看https://dynamic-datasource.com/guide/tx/Local.html#注意事项切换数据源失败原因

在使用时可以使用如下数据源配置,默认使用two数据源

datasource:
  druid:
    stat-view-servlet:
      enabled: false # 监控关闭
  dynamic:
    primary: two # 设置默认的数据源或者数据源组,默认值即为master
    strict: false # 设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.
    datasource:
      one:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://10.5.60.250:3306/aiopay_transaction2?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai&useAffectedRows=true
        username: root
        password: 111111
      two:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://10.5.60.250:3306/aiopay2?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai&useAffectedRows=true
        username: root
        password: 111111
    druid: # 以下是支持的全局默认值
      maxActive: 10
      initialSize: 2
      minIdle: 2
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: false
      filters: stat,slf4j
      maxWait: 60000

各个数据源都会有对应的业务service,每个对应数据源表的service最好只做本数据源的业务,避免跨源操作业务失败,需要跨源操作的service通过多个数据源的service组合来实现业务操作

数据源的配置使用@DS("one")这种注解,注解可以加在方法或者类上,方法上的注解优先于类上的注解,这里注意最好是在service上加注解,不要在mapper上加

 

跨数据源的业务如果要使用事务,请使用@DSTransactional注解,否则会出现切换数据源失败的情况,如果不存在跨数据源业务,事务可以直接使用@Transactional注解

这里需要注意:事务注解在方法上,不要放在类上,放在类上会导致该类 的所有方法都开启事务,影响效率,即使注解在方法上,也需要注意,事务注解的方法尽量只包含插入或者更新操作,不要包含查询操作,避免事务过大导致的异常,或者影响效率

你可能感兴趣的:(Spring,Boot)