springboot + mybatis + mysql + oracle + druid数据源连接池 + 自定义注解 + 切面实现多数据源动态切换,配置文件配置在application.yml中
时间: 2023-08-09 17:05:14 浏览: 143
好的,你的问题是关于如何在Spring Boot应用中实现多数据源动态切换,使用的技术包括Spring Boot、MyBatis、MySQL、Oracle、Druid数据源连接池、自定义注解和切面,并且配置文件使用application.yml格式。
首先,需要在pom.xml文件中添加相应的依赖:
```xml
<!--Spring Boot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--MyBatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!--Oracle-->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3.0.0</version>
</dependency>
<!--Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
```
接下来,需要在application.yml文件中配置数据源和MyBatis相关的属性,例如:
```yaml
spring:
datasource:
druid:
# 数据源1
db1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
# 数据源2
db2:
driver-class-name: oracle.jdbc.OracleDriver
url: jdbc:oracle:thin:@localhost:1521:ORCL
username: scott
password: tiger
# 默认数据源
url: jdbc:mysql://localhost:3306/db1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity
```
然后,需要定义一个自定义注解,用于标识哪些方法需要使用哪个数据源:
```java
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
String value() default "db1";
}
```
在数据源切换的时候,我们需要获取注解上指定的数据源名称,因此需要定义一个切面:
```java
@Aspect
@Component
public class DataSourceAspect {
@Around("@annotation(ds)")
public Object around(ProceedingJoinPoint point, DataSource ds) throws Throwable {
String dataSourceName = ds.value();
DynamicDataSource.setDataSource(dataSourceName);
try {
return point.proceed();
} finally {
DynamicDataSource.clearDataSource();
}
}
}
```
最后,需要定义一个动态数据源,用于实现数据源的切换:
```java
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> dataSourceHolder = new ThreadLocal<>();
@Override
protected Object determineCurrentLookupKey() {
return dataSourceHolder.get();
}
public static void setDataSource(String dataSourceName) {
dataSourceHolder.set(dataSourceName);
}
public static void clearDataSource() {
dataSourceHolder.remove();
}
}
```
至此,多数据源动态切换的配置就完成了。
阅读全文