SpringBoot基於AbstractRoutingDataSource如何實現多資料來源動態切換
一、場景
在生產業務中,有一些任務執行了耗時較長的查詢操作,在實時性要求不高的時候,我們希望將這些查詢sql分離出來,去從庫查詢,以減少應用對主資料庫的壓力。
一種方案是在設定檔中配置多個資料來源,然後透過配置類別來取得資料來源以及mapper相關的掃描配置,不同的資料來源配置不佟的mapper掃描位置,然後需要哪一個資料來源就注入哪一個mapper介面即可,這種方法比較簡單。特徵是透過mapper掃描位置區分資料來源。
一個可行的方案是事先設定一個預設的資料來源,同時定義多個其他的資料來源,利用aop實作註解方式來切換資料來源。對AbstractRoutingDataSource類別進行繼承是實現這種方案的關鍵。這是本文的重點。
二、原理
AbstractRoutingDataSource的多重資料來源動態切換的核心邏輯是:在程式運行時,把資料來源資料來源透過AbstractRoutingDataSource 動態織入到程式中,靈活的進行數據源切換。
基於AbstractRoutingDataSource的多資料來源動態切換,可以實現讀寫分離。邏輯如下:
/** * Retrieve the current target DataSource. Determines the * {@link #determineCurrentLookupKey() current lookup key}, performs * a lookup in the {@link #setTargetDataSources targetDataSources} map, * falls back to the specified * {@link #setDefaultTargetDataSource default target DataSource} if necessary. * @see #determineCurrentLookupKey() */ protected DataSource determineTargetDataSource() { Assert.notNull(this.resolvedDataSources, "DataSource router not initialized"); Object lookupKey = determineCurrentLookupKey(); DataSource dataSource = this.resolvedDataSources.get(lookupKey); if (dataSource == null && (this.lenientFallback || lookupKey == null)) { dataSource = this.resolvedDefaultDataSource; } if (dataSource == null) { throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]"); } return dataSource; } /** * Determine the current lookup key. This will typically be * implemented to check a thread-bound transaction context. * <p>Allows for arbitrary keys. The returned key needs * to match the stored lookup key type, as resolved by the * {@link #resolveSpecifiedLookupKey} method. */ @Nullable protected abstract Object determineCurrentLookupKey();
透過實作抽象方法determineCurrentLookupKey指定需要切換的資料來源
三、程式碼範例
範例中主要依賴
#com.alibaba .druid;tk.mybatis
定義一個類別用於關聯資料來源。透過 TheadLocal 來保存每個執行緒選擇哪個資料來源的標誌(key)
@Slf4j public class DynamicDataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static List<String> dataSourceIds = new ArrayList<String>(); public static void setDataSourceType(String dataSourceType) { log.info("设置当前数据源为{}",dataSourceType); contextHolder.set(dataSourceType); } public static String getDataSourceType() { return contextHolder.get() ; } public static void clearDataSourceType() { contextHolder.remove(); } public static boolean containsDataSource(String dataSourceId){ log.info("list = {},dataId={}", JSON.toJSON(dataSourceIds),dataSourceId); return dataSourceIds.contains(dataSourceId); } }
繼承
AbstractRoutingDataSource
public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DynamicDataSourceContextHolder.getDataSourceType(); } }
配置主資料庫master 與從資料庫slave(略)。資料來源設定可以從簡
@Configuration @tk.mybatis.spring.annotation.MapperScan(value = {"com.server.dal.dao"}) @ConditionalOnProperty(name = "java.druid.datasource.master.url") public class JavaDruidDataSourceConfiguration { private static final Logger logger = LoggerFactory.getLogger(JavaDruidDataSourceConfiguration.class); @Resource private JavaDruidDataSourceProperties druidDataSourceProperties; @Primary @Bean(name = "masterDataSource", initMethod = "init", destroyMethod = "close") @ConditionalOnMissingBean(name = "masterDataSource") public DruidDataSource javaReadDruidDataSource() { DruidDataSource result = new DruidDataSource(); try { // result.setName(druidDataSourceProperties.getName()); result.setUrl(druidDataSourceProperties.getUrl()); result.setUsername(druidDataSourceProperties.getUsername()); result.setPassword(druidDataSourceProperties.getPassword()); result.setConnectionProperties( "config.decrypt=false;config.decrypt.key=" + druidDataSourceProperties.getPwdPublicKey()); result.setFilters("config"); result.setMaxActive(druidDataSourceProperties.getMaxActive()); result.setInitialSize(druidDataSourceProperties.getInitialSize()); result.setMaxWait(druidDataSourceProperties.getMaxWait()); result.setMinIdle(druidDataSourceProperties.getMinIdle()); result.setTimeBetweenEvictionRunsMillis(druidDataSourceProperties.getTimeBetweenEvictionRunsMillis()); result.setMinEvictableIdleTimeMillis(druidDataSourceProperties.getMinEvictableIdleTimeMillis()); result.setValidationQuery(druidDataSourceProperties.getValidationQuery()); result.setTestWhileIdle(druidDataSourceProperties.isTestWhileIdle()); result.setTestOnBorrow(druidDataSourceProperties.isTestOnBorrow()); result.setTestOnReturn(druidDataSourceProperties.isTestOnReturn()); result.setPoolPreparedStatements(druidDataSourceProperties.isPoolPreparedStatements()); result.setMaxOpenPreparedStatements(druidDataSourceProperties.getMaxOpenPreparedStatements()); if (druidDataSourceProperties.isEnableMonitor()) { StatFilter filter = new StatFilter(); filter.setLogSlowSql(druidDataSourceProperties.isLogSlowSql()); filter.setMergeSql(druidDataSourceProperties.isMergeSql()); filter.setSlowSqlMillis(druidDataSourceProperties.getSlowSqlMillis()); List<Filter> list = new ArrayList<>(); list.add(filter); result.setProxyFilters(list); } } catch (Exception e) { logger.error("数据源加载失败:", e); } finally { result.close(); } return result; } }
注意主從資料庫的bean name
設定DynamicDataSource
targetDataSources 存放資料來源的k-v對
defaultTargetDataSource 存放預設資料來源
設定事務管理器和SqlSessionFactoryBean
@Configuration public class DynamicDataSourceConfig { private static final String MAPPER_LOCATION = "classpath*:sqlmap/dao/*Mapper.xml"; @Bean(name = "dynamicDataSource") public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DruidDataSource masterDataSource, @Qualifier("slaveDataSource") DruidDataSource slaveDataSource) { Map<Object, Object> targetDataSource = new HashMap<>(); DynamicDataSourceContextHolder.dataSourceIds.add("masterDataSource"); targetDataSource.put("masterDataSource", masterDataSource); DynamicDataSourceContextHolder.dataSourceIds.add("slaveDataSource"); targetDataSource.put("slaveDataSource", slaveDataSource); DynamicDataSource dataSource = new DynamicDataSource(); dataSource.setTargetDataSources(targetDataSource); dataSource.setDefaultTargetDataSource(masterDataSource); return dataSource; } @Primary @Bean(name = "javaTransactionManager") @ConditionalOnMissingBean(name = "javaTransactionManager") public DataSourceTransactionManager transactionManager(@Qualifier("dynamicDataSource") DynamicDataSource druidDataSource) { return new DataSourceTransactionManager(druidDataSource); } @Bean(name = "sqlSessionFactoryBean") public SqlSessionFactoryBean myGetSqlSessionFactory(@Qualifier("dynamicDataSource") DynamicDataSource dataSource) { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { sqlSessionFactoryBean.setMapperLocations(resolver.getResources(MAPPER_LOCATION)); } catch (IOException e) { e.printStackTrace(); } sqlSessionFactoryBean.setDataSource(dataSource); return sqlSessionFactoryBean; } }
定義一個註解用於指定資料來源
@Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface TargetDataSource { String value(); }
切面的業務邏輯。注意指定order,以確保在開啟事務之前執行 。
@Aspect @Slf4j @Order(-1) @Component public class DataSourceAop { @Before("@annotation(targetDataSource)") public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) { String dsId = targetDataSource.value(); if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) { log.error("数据源[{}]不存在,使用默认数据源 > {}" + targetDataSource.value() + point.getSignature()); } else { log.info("UseDataSource : {} > {}" + targetDataSource.value() + point.getSignature()); DynamicDataSourceContextHolder.setDataSourceType(targetDataSource.value()); } } @After("@annotation(targetDataSource)") public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource) { log.info("RevertDataSource : {} > {}"+targetDataSource.value()+point.getSignature()); DynamicDataSourceContextHolder.clearDataSourceType(); } }
以上略去了pom.xml和application.yml
使用範例
@Resource private ShopBillDOMapper shopBillDOMapper; //使用默认数据源 public ShopBillBO queryTestData(Integer id){ return shopBillDOMapper.getByShopBillId(id); } //切换到指定的数据源 @TargetDataSource("slaveDataSource") public ShopBill queryTestData2(Integer id){ return shopBillDOMapper.getByShopBillId(id); }
如果傳回不同的結果就成功了!
以上是SpringBoot基於AbstractRoutingDataSource如何實現多資料來源動態切換的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SublimeText3 Linux新版
SublimeText3 Linux最新版

Dreamweaver CS6
視覺化網頁開發工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中