在上一節(jié)我們通過(guò)Spring Boot集成了mybatis,在某些特定的場(chǎng)景下可能會(huì)需要我們使用到多數(shù)據(jù)源穆壕。本節(jié)來(lái)介紹Spring Boot集成mybatis多數(shù)據(jù)源的一種解決方案待牵。
- 由于我們會(huì)用到Spring Boot aop,因此在pom.xml中添加依賴(lài)
<!-- springboot-aop包,AOP切面注解,Aspectd等相關(guān)注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
- 在項(xiàng)目路徑下新建annotation包喇勋,自定義注解便于切換數(shù)據(jù)源
package com.example.demo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定義注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface DS {
String value() default "datasource1";
}
項(xiàng)目路徑下新建config包
- 新建DataSourceContextHolder.java類(lèi)缨该,用于保存本地?cái)?shù)據(jù)源
package com.example.demo.config;
/**
* 保存本地?cái)?shù)據(jù)源
*/
public class DataSourceContextHolder {
/**
* 默認(rèn)數(shù)據(jù)源
*/
public static final String DEFAULT_DS = "datasource1";
/**
* ThreadLocal之后會(huì)進(jìn)行講解
*/
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
// 設(shè)置數(shù)據(jù)源名
public static void setDB(String dbType) {
System.out.println("切換到{"+dbType+"}數(shù)據(jù)源");
contextHolder.set(dbType);
}
// 獲取數(shù)據(jù)源名
public static String getDB() {
return (contextHolder.get());
}
// 清除數(shù)據(jù)源名
public static void clearDB() {
contextHolder.remove();
}
}
- 新建DynamicDataSource.java類(lèi)用于獲取本地?cái)?shù)據(jù)源
package com.example.demo.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 獲取本地?cái)?shù)據(jù)源
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
System.out.println("數(shù)據(jù)源為"+DataSourceContextHolder.getDB());
return DataSourceContextHolder.getDB();
}
}
- 新建DataSourceConfig.java類(lèi)讀取配置
package com.example.demo.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* 多數(shù)據(jù)源配置類(lèi)
*
*/
@Configuration
public class DataSourceConfig {
//數(shù)據(jù)源1
@Bean(name = "datasource1")
@ConfigurationProperties(prefix = "spring.datasource.db1") // application.properteis中對(duì)應(yīng)屬性的前綴
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
//數(shù)據(jù)源2
@Bean(name = "datasource2")
@ConfigurationProperties(prefix = "spring.datasource.db2") // application.properteis中對(duì)應(yīng)屬性的前綴
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
/**
* 動(dòng)態(tài)數(shù)據(jù)源: 通過(guò)AOP在不同數(shù)據(jù)源之間動(dòng)態(tài)切換
* @return
*/
@Primary
@Bean(name = "dynamicDataSource")
public DataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 默認(rèn)數(shù)據(jù)源
dynamicDataSource.setDefaultTargetDataSource(dataSource1());
// 配置多數(shù)據(jù)源
Map<Object, Object> dsMap = new HashMap();
dsMap.put("datasource1", dataSource1());
dsMap.put("datasource2", dataSource2());
dynamicDataSource.setTargetDataSources(dsMap);
return dynamicDataSource;
}
/**
* 配置@Transactional注解事物
* @return
*/
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dynamicDataSource());
}
}
- 新建DynamicDataSourceAspect.java類(lèi)用于自定義注解 + AOP的方式實(shí)現(xiàn)數(shù)據(jù)源動(dòng)態(tài)切換。
package com.example.demo.config;
import com.example.demo.annotation.DS;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* 自定義注解 + AOP的方式實(shí)現(xiàn)數(shù)據(jù)源動(dòng)態(tài)切換川背。
*
*/
@Aspect
@Component
public class DynamicDataSourceAspect {
@Before("@annotation(DS)")
public void beforeSwitchDS(JoinPoint point, DS DS){
//獲得當(dāng)前訪(fǎng)問(wèn)的class
Class<?> className = point.getTarget().getClass();
//獲得訪(fǎng)問(wèn)的方法名
String methodName = point.getSignature().getName();
//得到方法的參數(shù)的類(lèi)型
Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
String dataSource = DataSourceContextHolder.DEFAULT_DS;
try {
// 得到訪(fǎng)問(wèn)的方法對(duì)象
Method method = className.getMethod(methodName, argClass);
// 判斷是否存在@DS注解
if (method.isAnnotationPresent(DS.class)) {
DS annotation = method.getAnnotation(DS.class);
// 取出注解中的數(shù)據(jù)源名
dataSource = annotation.value();
}
} catch (Exception e) {
e.printStackTrace();
}
// 切換數(shù)據(jù)源
DataSourceContextHolder.setDB(dataSource);
}
@After("@annotation(DS)")
public void afterSwitchDS(JoinPoint point, DS DS){
DataSourceContextHolder.clearDB();
}
}
以上代碼需要配合application.yml中的配置贰拿。yml中數(shù)據(jù)源配置如下:
spring:
datasource:
db1:
jdbc-url: jdbc:mysql:/localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&failOverReadOnly=false
username: test1
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
db2:
jdbc-url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&failOverReadOnly=false
username: test2
password: 123456
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
- 在啟動(dòng)類(lèi)中去掉數(shù)據(jù)源的自動(dòng)配置:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) - service方法小小的改造一下,在之前的基礎(chǔ)上加上自定義注解,通過(guò)注解來(lái)動(dòng)態(tài)切換數(shù)據(jù)源
@DS("datasource2")
public List<User> testMapper () {
return userMapper.selectAllUser();
}
啟動(dòng)項(xiàng)目熄云,調(diào)用controller中的接口膨更,從控制臺(tái)的輸出可以看到數(shù)據(jù)源已經(jīng)實(shí)現(xiàn)了動(dòng)態(tài)切換。
您的關(guān)注是我最大的動(dòng)力