最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot多數(shù)據(jù)源配置完整指南

 更新時間:2025年04月22日 14:09:19   作者:北辰alk  
在復(fù)雜的企業(yè)應(yīng)用中,經(jīng)常需要連接多個數(shù)據(jù)庫,Spring Boot 提供了靈活的多數(shù)據(jù)源配置方式,以下是詳細(xì)的實現(xiàn)方案,需要的朋友可以參考下

一、基礎(chǔ)多數(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ù)庫驅(qū)動 -->

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ù)源配置(運(yùn)行時切換)

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ù)源事務(wù)管理

1. JTA分布式事務(wù)(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. 使用分布式事務(wù)

@Service
public class OrderService {

    @Transactional // 跨數(shù)據(jù)源事務(wù)
    public void placeOrder(Order order) {
        // 操作主數(shù)據(jù)源
        primaryRepository.save(order);
        
        // 操作次數(shù)據(jù)源
        auditRepository.logOrder(order);
        
        // 如果此處拋出異常,兩個操作都會回滾
    }
}

六、最佳實踐

  1. 命名規(guī)范

    • 為每個數(shù)據(jù)源使用清晰的命名(如customerDS, orderDS)
    • 包結(jié)構(gòu)按數(shù)據(jù)源分離(com.example.repository.primary / .secondary)
  2. 連接池配置

spring.datasource.primary.hikari.maximum-pool-size=10
spring.datasource.secondary.hikari.maximum-pool-size=5
  1. 監(jiān)控指標(biāo)

    • 為每個數(shù)據(jù)源配置獨(dú)立的監(jiān)控
    • 使用Spring Actuator暴露數(shù)據(jù)源健康指標(biāo)
  2. 性能考慮

    • 高頻訪問的數(shù)據(jù)源使用更大的連接池
    • 讀寫分離場景考慮主從數(shù)據(jù)源
  3. 測試策略

    • 為每個數(shù)據(jù)源編寫?yīng)毩⒌臏y試類
    • 測試跨數(shù)據(jù)源事務(wù)的回滾行為

七、常見問題解決

問題1:循環(huán)依賴

// 解決方法:使用@DependsOn
@Bean
@DependsOn("dynamicDataSource")
public PlatformTransactionManager transactionManager() {
    return new DataSourceTransactionManager(dynamicDataSource());
}

問題2:MyBatis緩存沖突

// 解決方法:為每個SqlSessionFactory配置獨(dú)立的緩存環(huán)境
sqlSessionFactory.setConfiguration(configuration);
configuration.setEnvironment(new Environment(
    "primaryEnv", 
    transactionFactory, 
    dataSource
));

問題3:事務(wù)傳播行為異常

// 解決方法:明確指定事務(wù)管理器
@Transactional(transactionManager = "primaryTransactionManager")
public void primaryOperation() {...}

通過以上配置,Spring Boot應(yīng)用可以靈活地支持多數(shù)據(jù)源場景,無論是簡單的多庫連接還是復(fù)雜的動態(tài)數(shù)據(jù)源切換需求。根據(jù)實際業(yè)務(wù)場景選擇最適合的配置方式,并注意事務(wù)管理和性能調(diào)優(yōu)。

以上就是SpringBoot多數(shù)據(jù)源配置完整指南的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot多數(shù)據(jù)源配置的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 詳解Spring MVC自動為對象注入枚舉類型

    詳解Spring MVC自動為對象注入枚舉類型

    本篇文章主要介紹了Spring MVC自動為對象注入枚舉類型,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • 學(xué)會IDEA REST Client后就可以丟掉postman了

    學(xué)會IDEA REST Client后就可以丟掉postman了

    這篇文章主要介紹了學(xué)會IDEA REST Client后就可以丟掉postman了,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • 泛談Java中的不可變數(shù)據(jù)結(jié)構(gòu)

    泛談Java中的不可變數(shù)據(jù)結(jié)構(gòu)

    開發(fā)人員通常認(rèn)為擁有final引用,或者val在Kotlin或Scala中,足以使對象不可變。這篇博客文章深入研究了不可變引用和不可變數(shù)據(jù)結(jié)構(gòu),下面小編來和大家一起學(xué)習(xí)它
    2019-05-05
  • Mybatis如何自動生成數(shù)據(jù)庫表的實體類

    Mybatis如何自動生成數(shù)據(jù)庫表的實體類

    這篇文章主要介紹了Mybatis自動生成數(shù)據(jù)庫表的實體類的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • java中統(tǒng)一返回前端格式及統(tǒng)一結(jié)果處理返回詳解

    java中統(tǒng)一返回前端格式及統(tǒng)一結(jié)果處理返回詳解

    這篇文章主要介紹了統(tǒng)一結(jié)果處理的重要性,以及如何在SpringBoot項目中定義和使用統(tǒng)一結(jié)果返回類,通過構(gòu)造器私有化和靜態(tài)方法ok、error,提供了成功和失敗的統(tǒng)一響應(yīng)格式,需要的朋友可以參考下
    2025-02-02
  • 通過實例深入學(xué)習(xí)Java的Struts框架中的OGNL表達(dá)式使用

    通過實例深入學(xué)習(xí)Java的Struts框架中的OGNL表達(dá)式使用

    這篇文章主要通過實例介紹了Java的Strus框架中的OGNL表達(dá)式使用,Struts框架是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下
    2015-11-11
  • 用SpringBoot+Vue+uniapp小程序?qū)崿F(xiàn)在線房屋裝修管理系統(tǒng)

    用SpringBoot+Vue+uniapp小程序?qū)崿F(xiàn)在線房屋裝修管理系統(tǒng)

    這篇文章主要介紹了用SpringBoot+Vue+uniapp實現(xiàn)在線房屋裝修管理系統(tǒng),針對裝修樣板信息管理混亂,出錯率高,信息安全性差,勞動強(qiáng)度大,費(fèi)時費(fèi)力等問題開發(fā)了這套系統(tǒng),需要的朋友可以參考下
    2023-03-03
  • 詳解Spring Data JPA中Repository的接口查詢方法

    詳解Spring Data JPA中Repository的接口查詢方法

    repository代理有兩種方式從方法名中派生出特定存儲查詢:通過直接從方法名派生查詢和通過使用一個手動定義的查詢。本文將通過示例詳細(xì)講解Spring Data JPA中Repository的接口查詢方法,需要的可以參考一下
    2022-04-04
  • 使用mybatis攔截器處理敏感字段

    使用mybatis攔截器處理敏感字段

    這篇文章主要介紹了mybatis攔截器處理敏感字段方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • SpringBoot實現(xiàn)抽獎算法的示例代碼

    SpringBoot實現(xiàn)抽獎算法的示例代碼

    這篇文章主要為大家詳細(xì)介紹了如何通過SpringBoot實現(xiàn)抽獎算法,文中的示例代碼簡潔易懂,具有一定的參考價值,感興趣的小伙伴可以了解一下
    2023-06-06

最新評論

会泽县| 洞口县| 社旗县| 永德县| 金门县| 仪征市| 综艺| 黔西县| 平原县| 阜南县| 吉木萨尔县| 汝城县| 武平县| 德江县| 宜阳县| 威信县| 富裕县| 新蔡县| 乌海市| 临清市| 黄石市| 繁峙县| 新巴尔虎左旗| 常山县| 龙海市| 连云港市| 弋阳县| 闻喜县| 巴青县| 英德市| 高州市| 洪江市| 镇宁| 灵武市| 肃北| 紫阳县| 昌图县| 綦江县| 南皮县| 珠海市| 濉溪县|