SpringBoot多數(shù)據(jù)源配置完整指南
更新時間:2025年04月22日 14:09:19 作者:北辰alk
在復雜的企業(yè)應用中,經(jīng)常需要連接多個數(shù)據(jù)庫,Spring Boot 提供了靈活的多數(shù)據(jù)源配置方式,以下是詳細的實現(xiàn)方案,需要的朋友可以參考下
一、基礎多數(shù)據(jù)源配置
1. 添加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 或者使用其他數(shù)據(jù)庫驅動 -->
2. 配置多個數(shù)據(jù)源
# 主數(shù)據(jù)源 spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=root spring.datasource.primary.password=123456 spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver # 次數(shù)據(jù)源 spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2 spring.datasource.secondary.username=root spring.datasource.secondary.password=123456 spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
3. 配置數(shù)據(jù)源Bean
@Configuration public class DataSourceConfig { // 主數(shù)據(jù)源 @Bean @Primary @ConfigurationProperties(prefix="spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } // 次數(shù)據(jù)源 @Bean @ConfigurationProperties(prefix="spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } }
二、JPA多數(shù)據(jù)源配置
1. 配置主數(shù)據(jù)源JPA
@Configuration @EnableTransactionManagement @EnableJpaRepositories( basePackages = "com.example.repository.primary", entityManagerFactoryRef = "primaryEntityManagerFactory", transactionManagerRef = "primaryTransactionManager" ) public class PrimaryJpaConfig { @Autowired @Qualifier("primaryDataSource") private DataSource primaryDataSource; @Primary @Bean public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(primaryDataSource) .packages("com.example.entity.primary") .persistenceUnit("primaryPersistenceUnit") .properties(jpaProperties()) .build(); } private Map<String, Object> jpaProperties() { Map<String, Object> props = new HashMap<>(); props.put("hibernate.hbm2ddl.auto", "update"); props.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); return props; } @Primary @Bean public PlatformTransactionManager primaryTransactionManager( @Qualifier("primaryEntityManagerFactory") EntityManagerFactory emf) { return new JpaTransactionManager(emf); } }
2. 配置次數(shù)據(jù)源JPA
@Configuration @EnableTransactionManagement @EnableJpaRepositories( basePackages = "com.example.repository.secondary", entityManagerFactoryRef = "secondaryEntityManagerFactory", transactionManagerRef = "secondaryTransactionManager" ) public class SecondaryJpaConfig { @Autowired @Qualifier("secondaryDataSource") private DataSource secondaryDataSource; @Bean public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(secondaryDataSource) .packages("com.example.entity.secondary") .persistenceUnit("secondaryPersistenceUnit") .properties(jpaProperties()) .build(); } private Map<String, Object> jpaProperties() { Map<String, Object> props = new HashMap<>(); props.put("hibernate.hbm2ddl.auto", "update"); props.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect"); return props; } @Bean public PlatformTransactionManager secondaryTransactionManager( @Qualifier("secondaryEntityManagerFactory") EntityManagerFactory emf) { return new JpaTransactionManager(emf); } }
三、MyBatis多數(shù)據(jù)源配置
1. 主數(shù)據(jù)源配置
@Configuration @MapperScan( basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory" ) public class PrimaryMyBatisConfig { @Primary @Bean @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean public SqlSessionFactory primarySqlSessionFactory( @Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setMapperLocations( new PathMatchingResourcePatternResolver() .getResources("classpath:mapper/primary/*.xml")); return sessionFactory.getObject(); } @Primary @Bean public SqlSessionTemplate primarySqlSessionTemplate( @Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
2. 次數(shù)據(jù)源配置
@Configuration @MapperScan( basePackages = "com.example.mapper.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory" ) public class SecondaryMyBatisConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory secondarySqlSessionFactory( @Qualifier("secondaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setMapperLocations( new PathMatchingResourcePatternResolver() .getResources("classpath:mapper/secondary/*.xml")); return sessionFactory.getObject(); } @Bean public SqlSessionTemplate secondarySqlSessionTemplate( @Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } }
四、動態(tài)數(shù)據(jù)源配置(運行時切換)
1. 抽象路由數(shù)據(jù)源
public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSourceType(); } }
2. 數(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(); } }
3. 配置動態(tài)數(shù)據(jù)源
@Configuration public class DynamicDataSourceConfig { @Bean @ConfigurationProperties(prefix="spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix="spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean public DataSource dynamicDataSource( @Qualifier("primaryDataSource") DataSource primaryDataSource, @Qualifier("secondaryDataSource") DataSource secondaryDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("primary", primaryDataSource); targetDataSources.put("secondary", secondaryDataSource); DynamicDataSource dynamicDataSource = new DynamicDataSource(); dynamicDataSource.setTargetDataSources(targetDataSources); dynamicDataSource.setDefaultTargetDataSource(primaryDataSource); return dynamicDataSource; } }
4. 使用AOP切換數(shù)據(jù)源
@Aspect @Component public class DataSourceAspect { @Pointcut("@annotation(com.example.annotation.TargetDataSource)") public void dataSourcePointCut() {} @Before("dataSourcePointCut()") public void before(JoinPoint point) { MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); TargetDataSource ds = method.getAnnotation(TargetDataSource.class); if (ds == null) { DataSourceContextHolder.setDataSourceType("primary"); } else { DataSourceContextHolder.setDataSourceType(ds.value()); } } @After("dataSourcePointCut()") public void after(JoinPoint point) { DataSourceContextHolder.clearDataSourceType(); } }
5. 自定義注解
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface TargetDataSource { String value() default "primary"; }
6. 使用示例
@Service public class UserService { @Autowired private UserMapper userMapper; // 使用主數(shù)據(jù)源 public User getPrimaryUser(Long id) { return userMapper.selectById(id); } // 使用次數(shù)據(jù)源 @TargetDataSource("secondary") public User getSecondaryUser(Long id) { return userMapper.selectById(id); } }
五、多數(shù)據(jù)源事務管理
1. JTA分布式事務(Atomikos)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jta-atomikos</artifactId> </dependency>
2. 配置JTA數(shù)據(jù)源
# 主數(shù)據(jù)源 spring.jta.atomikos.datasource.primary.unique-resource-name=primaryDS spring.jta.atomikos.datasource.primary.xa-data-source-class-name=com.mysql.cj.jdbc.MysqlXADataSource spring.jta.atomikos.datasource.primary.xa-properties.url=jdbc:mysql://localhost:3306/db1 spring.jta.atomikos.datasource.primary.xa-properties.user=root spring.jta.atomikos.datasource.primary.xa-properties.password=123456 # 次數(shù)據(jù)源 spring.jta.atomikos.datasource.secondary.unique-resource-name=secondaryDS spring.jta.atomikos.datasource.secondary.xa-data-source-class-name=com.mysql.cj.jdbc.MysqlXADataSource spring.jta.atomikos.datasource.secondary.xa-properties.url=jdbc:mysql://localhost:3306/db2 spring.jta.atomikos.datasource.secondary.xa-properties.user=root spring.jta.atomikos.datasource.secondary.xa-properties.password=123456
3. 使用分布式事務
@Service public class OrderService { @Transactional // 跨數(shù)據(jù)源事務 public void placeOrder(Order order) { // 操作主數(shù)據(jù)源 primaryRepository.save(order); // 操作次數(shù)據(jù)源 auditRepository.logOrder(order); // 如果此處拋出異常,兩個操作都會回滾 } }
六、最佳實踐
命名規(guī)范:
- 為每個數(shù)據(jù)源使用清晰的命名(如customerDS, orderDS)
- 包結構按數(shù)據(jù)源分離(com.example.repository.primary / .secondary)
連接池配置:
spring.datasource.primary.hikari.maximum-pool-size=10 spring.datasource.secondary.hikari.maximum-pool-size=5
監(jiān)控指標:
- 為每個數(shù)據(jù)源配置獨立的監(jiān)控
- 使用Spring Actuator暴露數(shù)據(jù)源健康指標
性能考慮:
- 高頻訪問的數(shù)據(jù)源使用更大的連接池
- 讀寫分離場景考慮主從數(shù)據(jù)源
測試策略:
- 為每個數(shù)據(jù)源編寫獨立的測試類
- 測試跨數(shù)據(jù)源事務的回滾行為
七、常見問題解決
問題1:循環(huán)依賴
// 解決方法:使用@DependsOn @Bean @DependsOn("dynamicDataSource") public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dynamicDataSource()); }
問題2:MyBatis緩存沖突
// 解決方法:為每個SqlSessionFactory配置獨立的緩存環(huán)境 sqlSessionFactory.setConfiguration(configuration); configuration.setEnvironment(new Environment( "primaryEnv", transactionFactory, dataSource ));
問題3:事務傳播行為異常
// 解決方法:明確指定事務管理器 @Transactional(transactionManager = "primaryTransactionManager") public void primaryOperation() {...}
通過以上配置,Spring Boot應用可以靈活地支持多數(shù)據(jù)源場景,無論是簡單的多庫連接還是復雜的動態(tài)數(shù)據(jù)源切換需求。根據(jù)實際業(yè)務場景選擇最適合的配置方式,并注意事務管理和性能調優(yōu)。
以上就是SpringBoot多數(shù)據(jù)源配置完整指南的詳細內容,更多關于SpringBoot多數(shù)據(jù)源配置的資料請關注腳本之家其它相關文章!
相關文章
解讀controller層,service層,mapper層,entity層的作用與聯(lián)系
這篇文章主要介紹了關于controller層,service層,mapper層,entity層的作用與聯(lián)系,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11IDEA的Mybatis Log Plugin插件配置和使用詳解
這篇文章主要介紹了IDEA的Mybatis Log Plugin插件配置和使用,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09