1.@DS概述
????????@DS是自定義注解,可以作用于方法或類上,用于切換數據源。當注解添加到類上時,意味著此類里的方法都使用此數據源;當注解添加到方法上時,意味著此方法上使用的數據源優先級高于其他一切配置。
2.@DS使用
2.1 導入依賴
<dependency>
????????<groupId>com.baomidou</groupId>
????????<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
????????<version>3.2.1</version>
</dependency>
2.2? 配置數據源
spring:# 數據源配置datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverdynamic:strict: trueprimary: test1datasource:main:url: jdbc:mysql://127.0.0.1:3306/intelligent?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&useTimezone=true&serverTimezone=Asia/Shanghaiusername: rootpassword: test:url: jdbc:mysql://127.0.0.1:3306/integration_platform?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&useTimezone=true&serverTimezone=Asia/Shanghaiusername: rootpassword: test1:url: jdbc:mysql://127.0.0.1:3306/scheduled_tasks?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&useTimezone=true&serverTimezone=Asia/Shanghaiusername: rootpassword:
2.3 使用@DS注解
????????在需要切換數據源的地方,使用@DS注解并指定需要切換到的數據源名稱
@Service
@DS("test")
public class demoServiceImpl extends ServiceImpl<demoMapper, demoPO> implements demoService {}
2.4 集成Durid
????????使用@DS時集成Druid并排除原生Druid的快速配置類,主要是為了實現更細粒度的數據源切換和擴展,提高應用程序的數據庫訪問性能、系統安全性和可維護性。
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
@MapperScan("com.luobei.demo.modules.*.*.mapper")
@EnableTransactionManagement
public class DemoAppRun {public static void main(String[] args) {SpringApplication.run(DemoAppRun.class, args);}
}