SpringBoot 自定義注解 實現多數據源

SpringBoot自定義注解實現多數據源前置學習

需要了解 注解、Aop、SpringBoot整合Mybatis的使用 。
數據準備基礎項目代碼:https://gitee.com/J_look/spring-boot-all-demo
數據庫SQL 項目中有提供,修改基本信息即可
行動起來添加依賴
利用 AOP 可以實現對某些代碼的解耦,不需要硬編碼編寫 。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>開啟AOP支持
也可以像圖中一樣 , 也開啟事務管理器,下文會演示事務失效的問題 。

SpringBoot 自定義注解 實現多數據源

文章插圖
定義枚舉
這里定義的枚舉,代表我們不同的數據庫 。
public enum DataSourceType {MYSQL_DATASOURCE1,MYSQL_DATASOURCE2,}定義數據源管理器
由于本人實力原因,解答不了大家這里的疑惑 。大致功能 通過修改本地線程的值,來實現數據源的切換 。
@Component@Primarypublic class DataSourceManagement extends AbstractRoutingDataSource {public static ThreadLocal<String> flag = new ThreadLocal<>();/*** 注入數據源*/@Resourceprivate DataSource mysqlDataSource1;/*** 注入數據源*/@Resourceprivate DataSource mysqlDataSource2;public DataSourceManagement() {flag.set(DataSourceType.MYSQL_DATASOURCE1.name());}@Overrideprotected Object determineCurrentLookupKey() {return flag.get();}@Overridepublic void afterPropertiesSet() {Map<Object, Object> targetDataSource = new ConcurrentHashMap<>();targetDataSource.put(DataSourceType.MYSQL_DATASOURCE1.name(), mysqlDataSource1);targetDataSource.put(DataSourceType.MYSQL_DATASOURCE2.name(), mysqlDataSource2);// 設置數據源來源super.setTargetDataSources(targetDataSource);// 設置默認數據源super.setDefaultTargetDataSource(mysqlDataSource1);super.afterPropertiesSet();}}自定義注解
@target:表示自定義注解能用在哪里
【SpringBoot 自定義注解 實現多數據源】@Target({ElementType.TYPE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface TargetDataSource {DataSourceType value() default DataSourceType.MYSQL_DATASOURCE1;}定義切面類
可以看到,我們的切面類采用的是環繞通知,博主在寫這篇文章之前,做過大量測試 , 也參考過比較多的文章,總結以下幾點:
  • 采用前置通知,雖然能實現數據源的切換,但是會導致事務失效 。(推薦視頻)
  • 采用環繞通知,事務不會失效,但是切換數據源卻實現不了 。(由Bean的加載順序導致的,下文中的@Order就可以解決 , @Transactional默認級別是最后加載 ??梢圆榭慈罩拘畔⒅獣?。)
@Component@Aspect@Slf4j@Order(Ordered.LOWEST_PRECEDENCE-1) // Bean加載順序public class TargetDataSourceAspect {@Around("@within(TargetDataSource) || @annotation(TargetDataSource)")public Object beforeNoticeUpdateDataSource(ProceedingJoinPoint joinPoint) {TargetDataSource annotation = null;Class<? extends Object> target = joinPoint.getTarget().getClass();if (target.isAnnotationPresent(TargetDataSource.class)) {// 判斷類上是否標注著注解annotation = target.getAnnotation(TargetDataSource.class);log.info("類上標注了注解");} else {Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();if (method.isAnnotationPresent(TargetDataSource.class)) {// 判斷方法上是否標注著注解,如果類和方法上都沒有標注,則報錯annotation = method.getAnnotation(TargetDataSource.class);log.info("方法上標注了注解");} else {throw new RuntimeException("@TargetDataSource注解只能用于類或者方法上, 錯誤出現在:[" +target.toString() + " " + method.toString() + "];");}}// 切換數據源DataSourceManagement.flag.set(annotation.value().name());Object result = null;try {// 執行目標代碼result = joinPoint.proceed();} catch (Throwable e) {e.printStackTrace();}return result;}}Service
SpringBoot 自定義注解 實現多數據源

文章插圖
啟動測試類:
import look.word.datasource.service.BookService;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import javax.annotation.Resource;/** * @author : look-word * 2022-10-10 23:11 **/@SpringBootTestpublic class TestBookMapper {@Resourceprivate BookService bookService;@Testvoid updatePrice() {System.out.println(bookService.updatePrice(1, 777));}}
觀察執行日志可知,數據源的切換實現了 , 事務也沒有失效 。

推薦閱讀