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);}
}