SpringBoot實現多數據源連接和切換的完整方案
前言
在 Spring Boot 中實現多數據源連接和切換,可以通過以下幾種方案來實現,具體取決于項目的需求、數據庫的使用模式和管理的復雜性。以下是一個常見的多數據源切換的實現方案,使用 AbstractRoutingDataSource 來動態(tài)選擇數據源。
一、多數據源配置與切換方案
在多數據源場景中,通常有如下步驟:
- 配置多個數據源的
DataSourcebean。 - 使用
AbstractRoutingDataSource來動態(tài)切換數據源。 - 使用
ThreadLocal存儲當前的數據庫類型或數據源標識符。 - 配置數據源切換的邏輯,例如基于當前的用戶、請求路徑、服務標識等來選擇不同的數據源。
二、實現步驟
1. 創(chuàng)建多個DataSource配置類
首先,為每個數據源創(chuàng)建單獨的配置類,通常你會在 application.yml 或 application.properties 中配置每個數據源的連接信息。
spring:
datasource:
# 默認數據源配置
primary:
url: jdbc:mysql://localhost:3306/primary_db
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 10
# 第二數據源配置
secondary:
url: jdbc:mysql://localhost:3306/secondary_db
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 10
2. 創(chuàng)建DataSource配置類
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
3. 創(chuàng)建動態(tài)數據源路由類
AbstractRoutingDataSource 允許我們在運行時根據某些條件動態(tài)選擇數據源。
@Configuration
public class DynamicDataSourceConfig {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean
public DataSource dataSource() {
// 創(chuàng)建一個路由數據源
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setDefaultTargetDataSource(primaryDataSource); // 默認數據源
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put("primary", primaryDataSource);
targetDataSources.put("secondary", secondaryDataSource);
dataSource.setTargetDataSources(targetDataSources);
return dataSource;
}
}
4. 實現DynamicDataSource類
DynamicDataSource 是繼承自 AbstractRoutingDataSource,它通過 determineCurrentLookupKey() 方法來動態(tài)確定當前的數據源。
public class DynamicDataSource extends AbstractRoutingDataSource {
// 從 ThreadLocal 獲取當前的數據庫標識
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceType();
}
}
5. 創(chuàng)建DataSourceContextHolder來存儲當前的數據源標識
使用 ThreadLocal 來保持當前線程的數據庫標識,以便在不同的數據源之間切換。
public class DataSourceContextHolder {
// 使用 ThreadLocal 存儲當前線程的數據源標識
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSourceType() {
return contextHolder.get();
}
public static void clearDataSourceType() {
contextHolder.remove();
}
}
6. AOP 方式切換數據源
為了在運行時動態(tài)切換數據源,通常會使用 AOP 切面來攔截方法執(zhí)行并指定數據源。
@Aspect
@Component
public class DataSourceAspect {
// 通過注解來指定使用哪個數據源
@Before("@annotation(dataSource)")
public void switchDataSource(DataSourceType dataSource) {
// 切換數據源
DataSourceContextHolder.setDataSourceType(dataSource.value());
}
@After("@annotation(dataSource)")
public void clearDataSource(DataSourceType dataSource) {
// 清理數據源標識,避免影響其他線程
DataSourceContextHolder.clearDataSourceType();
}
}
7. 自定義注解來指定數據源
創(chuàng)建一個自定義注解 DataSourceType,用于指定當前方法執(zhí)行時需要使用的數據源。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSourceType {
String value() default "primary"; // 數據源標識,默認使用primary數據源
}
8. 在 Service 層使用注解指定數據源
在 Service 層,可以使用剛才創(chuàng)建的 @DataSourceType 注解來指定不同的方法使用不同的數據源。
@Service
public class UserService {
@DataSourceType("primary")
public List<User> getPrimaryUsers() {
// 查詢主數據庫
return userRepository.findAll();
}
@DataSourceType("secondary")
public List<User> getSecondaryUsers() {
// 查詢次數據庫
return secondaryUserRepository.findAll();
}
}
總結
- 數據源配置:為每個數據源配置
DataSourceBean。 - 動態(tài)數據源路由:使用
AbstractRoutingDataSource來實現動態(tài)切換數據源。 - ThreadLocal存儲:使用
ThreadLocal存儲和獲取當前線程的數據源標識。 - AOP切換數據源:使用 AOP 來攔截方法并切換數據源。
- 注解方式指定數據源:通過自定義注解來指定方法使用的具體數據源。
這種方式比較靈活,能夠在運行時根據業(yè)務需求選擇不同的數據源,適用于多數據源的場景,尤其是分庫分表、讀寫分離等復雜應用場景。
到此這篇關于SpringBoot實現多數據源連接和切換的完整方案的文章就介紹到這了,更多相關SpringBoot多數據源連接和切換內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解如何為SpringBoot項目中的自定義配置添加IDE支持
這篇文章主要介紹了詳解如何為SpringBoot項目中的自定義配置添加IDE支持,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02
Java+Springboot搭建一個在線網盤文件分享系統(tǒng)
本主要介紹了通過springboot+freemark+jpa+MySQL實現的在線網盤文件分享系統(tǒng),其功能跟百度網盤非常類似,可以實現文件的上傳、移動、復制、下載等,需要的可以參考一下2021-11-11

