SpringBoot中實(shí)現(xiàn)多數(shù)據(jù)源連接和切換的方案
引言
在Spring Boot中,通過AbstractRoutingDataSource實(shí)現(xiàn)多數(shù)據(jù)源連接是一種常見的做法。這種技術(shù)允許你在運(yùn)行時(shí)動(dòng)態(tài)地切換數(shù)據(jù)源,從而支持對(duì)多個(gè)數(shù)據(jù)庫的操作。Spring Boot中配置和使用AbstractRoutingDataSource來實(shí)現(xiàn)多數(shù)據(jù)源連接。
1. 添加依賴
pom.xml文件的依賴,比如Spring Data JPA和數(shù)據(jù)庫驅(qū)動(dòng):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 其他依賴 -->
</dependencies>
2. 配置數(shù)據(jù)源屬性
在application.yml或application.properties中配置多個(gè)數(shù)據(jù)源的信息。例如:
spring:
datasource:
primary:
url: jdbc:mysql://localhost:3306/primary_db
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
secondary:
url: jdbc:mysql://localhost:3306/secondary_db
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
3. 創(chuàng)建數(shù)據(jù)源配置類
創(chuàng)建兩個(gè)數(shù)據(jù)源配置類,分別用于配置主數(shù)據(jù)源和次數(shù)據(jù)源。
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@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();
}
}
4. 創(chuàng)建自定義數(shù)據(jù)源路由類
擴(kuò)展AbstractRoutingDataSource類,并根據(jù)上下文信息動(dòng)態(tài)返回?cái)?shù)據(jù)源。
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceType();
}
}
5. 創(chuàng)建數(shù)據(jù)源上下文持有者
用于在運(yùn)行時(shí)設(shè)置和獲取當(dāng)前的數(shù)據(jù)源類型。
public class DataSourceContextHolder {
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. 配置多數(shù)據(jù)源
將數(shù)據(jù)源配置到Spring上下文中,并指定默認(rèn)的數(shù)據(jù)源。
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = "com.example.repository",
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager"
)
public class DataSourceRoutingConfig {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean
public DataSource dataSource() {
DynamicRoutingDataSource routingDataSource = new DynamicRoutingDataSource();
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put("primary", primaryDataSource);
targetDataSources.put("secondary", secondaryDataSource);
routingDataSource.setTargetDataSources(targetDataSources);
routingDataSource.setDefaultTargetDataSource(primaryDataSource);
return routingDataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(dataSource())
.packages("com.example.entity")
.persistenceUnit("multiple-pu")
.build();
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
7. 使用AOP切換數(shù)據(jù)源
通過AOP在方法執(zhí)行前設(shè)置數(shù)據(jù)源類型,并在方法執(zhí)行后清除。
@Aspect
@Component
public class DataSourceAspect {
@Before("@annotation(targetDataSource)")
public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) throws Throwable {
DataSourceContextHolder.setDataSourceType(targetDataSource.value());
}
@After("@annotation(targetDataSource)")
public void clearDataSource(JoinPoint point, TargetDataSource targetDataSource) {
DataSourceContextHolder.clearDataSourceType();
}
}
自定義注解TargetDataSource:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetDataSource {
String value();
}
8. 使用自定義注解切換數(shù)據(jù)源
在需要使用特定數(shù)據(jù)源的方法或類上使用@TargetDataSource注解。
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@TargetDataSource("primary")
public User findUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
@TargetDataSource("secondary")
public User findUserBySecondaryId(Long id) {
// 假設(shè)secondary數(shù)據(jù)庫有一個(gè)類似的表結(jié)構(gòu)
return userRepository.findById(id).orElse(null);
}
}
到此這篇關(guān)于SpringBoot中實(shí)現(xiàn)多數(shù)據(jù)源連接和切換的方案的文章就介紹到這了,更多相關(guān)SpringBoot多數(shù)據(jù)源連接和切換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot項(xiàng)目如何配置多數(shù)據(jù)源
- SpringBoot實(shí)現(xiàn)JPA多數(shù)據(jù)源配置小結(jié)
- SpringBoot實(shí)現(xiàn)多數(shù)據(jù)源配置的示例詳解
- 淺析SpringBoot多數(shù)據(jù)源實(shí)現(xiàn)方案
- springboot項(xiàng)目實(shí)現(xiàn)多數(shù)據(jù)源配置使用dynamic-datasource-spring-boot-starter的操作步驟
- springboot配置多數(shù)據(jù)源的一款框架(dynamic-datasource-spring-boot-starter)
- SpringBoot利用dynamic-datasource-spring-boot-starter解決多數(shù)據(jù)源問題
相關(guān)文章
mybatis-plus分頁查詢的實(shí)現(xiàn)示例
這篇文章主要介紹了mybatis-plus分頁查詢的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
SpringBoot注冊(cè)第三方Bean的方法總結(jié)
眾所周知,SpringBoot默認(rèn)會(huì)掃描啟動(dòng)類所在的包及其子包,一般我們都是在需要的類上通過注解的方式去將Bean注冊(cè)交給IOC進(jìn)行管理,但是注冊(cè)第三方Bean的方案卻不支持,所以本文給大家介紹了SpringBoot注冊(cè)第三方Bean的方法,需要的朋友可以參考下2024-01-01
Java?C++題解leetcode消失的兩個(gè)數(shù)字實(shí)例
這篇文章主要介紹了Java?C++題解leetcode消失的兩個(gè)數(shù)字實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
GSON實(shí)現(xiàn)Java對(duì)象與JSON格式對(duì)象相互轉(zhuǎn)換的完全教程
GSON是Google編寫并在在GitHub上開源的Java序列化與反序列化JSON的類庫,今天我們就來總結(jié)一下使用GSON實(shí)現(xiàn)Java對(duì)象與JSON格式對(duì)象相互轉(zhuǎn)換的完全教程2016-06-06
Java中l(wèi)ist.contains()的用法及拓展
List集合相信大家在開發(fā)過程中幾乎都會(huì)用到,有時(shí)候難免會(huì)遇到集合里的數(shù)據(jù)是重復(fù)的,需要進(jìn)行去除,下面這篇文章主要給大家介紹了關(guān)于Java中l(wèi)ist.contains()的用法及拓展的相關(guān)資料,需要的朋友可以參考下2023-03-03
spring項(xiàng)目實(shí)現(xiàn)國際化流程解析
SpringBoot實(shí)現(xiàn)國際化(i18n)的步驟包括創(chuàng)建國際化資源文件、配置application.yml、自定義LocaleResolver和LocaleChangeInterceptor、在代碼中使用MessageSource獲取國際化消息,本文介紹spring項(xiàng)目實(shí)現(xiàn)國際化流程,感興趣的朋友一起看看吧2026-01-01
SpringBoot使用CORS實(shí)現(xiàn)無縫跨域的方法實(shí)現(xiàn)
CORS 是一種在服務(wù)端設(shè)置響應(yīng)頭部信息的機(jī)制,允許特定的源進(jìn)行跨域訪問,本文主要介紹了SpringBoot使用CORS實(shí)現(xiàn)無縫跨域的方法實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10

