网站开发深,天津设计公司排行榜,wordpress 商业,西安seo技术前言
最近接到一个新需求需要处理多数据源的问题 #xff0c;今天就来和大家一起学习一下。
一、使用步骤
1.引入库 代码如下#xff08;示例#xff09;#xff1a; !--配置多数据源--dependencygroupIdcom.baomidou/groupIdartif…前言
最近接到一个新需求需要处理多数据源的问题 今天就来和大家一起学习一下。
一、使用步骤
1.引入库 代码如下示例 !--配置多数据源--dependencygroupIdcom.baomidou/groupIdartifactIddynamic-datasource-spring-boot-starter/artifactIdversion3.5.0/version/dependency2.Springboot的application.yml中进行配置
代码如下示例 datasource:dynamic:primary: master #设置默认的数据源或者数据源组,默认值即为masterstrict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源datasource:master:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://xxx:3306/demo?useSSLfalseuseUnicodetruecharacterEncodingutf-8zeroDateTimeBehaviorconvertToNulltransformedBitIsBooleantrueserverTimezoneGMT%2B8nullCatalogMeansCurrenttrueallowPublicKeyRetrievaltrueusername: xxxpassword: xxxtest:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://xxx2:3306/test?serverTimezoneGMT%2B8useUnicodetruecharacterEncodingutf-8useSSLfalseallowMultiQueriestrueallowPublicKeyRetrievaltrueusername: xxxpassword: xxx配置了两个数据源master与test其中选择master作为默认数据源对应primary主要的配置 3. ServiceImpl层注解使用实例可以注解在方法上或类上
1.类上注解
Service
Slf4j
DS(test)//使用test数据源
public class TestServiceImpl implements TestService {Resourceprivate TestMapper testMapper;Overridepublic Integer saveTest(Test test) {return testMapper.insertTest(test);}
}2.方法上注解mapper上面也需要注解
Service
Slf4j
public class TestServiceImpl implements TestService {Resourceprivate TestMapper testMapper;OverrideDS(test)//使用test数据源public Integer saveTest(Test test) {return testMapper.insertTest(test);}
}4. 配置启动类
SpringBootApplication(exclude {DataSourceAutoConfiguration.class})
EnableScheduling
SpringBootApplication(exclude {DataSourceAutoConfiguration.class})
public class Application {public static void main(String[] args) {SinoApplication.single(ModuleInfo.ModuleName, Application.class, args);}
}
5. 配置Dockerfile文件 -Dspring.datasource.dynamic.enabledtrue,\失效场景解决方案 使用动态数据源DS时Transactional使用可能会照成DS失效。 解决方案
1.去掉事务不建议 2.DS切换数据源的方法添加事务传播属性Transactional(propagation Propagation.REQUIRES_NEW, rollbackFor Exception.class) 3.去掉DS切换数据源方法的事务主方法用DSTransactional注解。
总结
以上就是今天要讲的内容本文仅仅简单介绍了DS注解的使用