Spring Boot 多数据源配置

本文详细介绍了在Spring Boot项目中配置多数据源的步骤,包括在pom.xml添加依赖,配置application.yml,创建主库和从库的配置文件DataSourcePrimaryConfig.java和DataSourceSecondaryConfig.java,以及编写测试Controller验证配置效果。通过访问特定URL确认多数据源配置成功,并提供源码链接及扩展信息,说明如何添加更多数据源。
摘要由CSDN通过智能技术生成

       在项目中难免会有跨库操作的场景,此时就需要一个项目连接两个甚至多个数据源,以下说明spring boot多数据源的一些基本配置。

一、在pom.xml加入依赖jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

二、在application.yml 或application.properties文件中加入以下配置

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 5
    primary-db:
      url: jdbc:mysql://localhost:3306/db1?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
      username: root
      password: 123456
    second-db:
      url: jdbc:mysql://localhost:3306/db2?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
      username: root
      password: 654321
  jpa:
    database: MYSQL
    show-sql: true
    open-in-view: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect
    hibernate:
      dll-auto: none

三、添加主库配置文件DataSourcePrimaryConfig.java

package com.example.multidata.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Properties;


@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(ent
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot 多数据源配置可以通过以下步骤实现: 1. 在 application.properties 或 application.yml 文件中配置多个数据源的连接信息,例如: ``` spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1 spring.datasource.primary.username=root spring.datasource.primary.password=123456 spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2 spring.datasource.secondary.username=root spring.datasource.secondary.password=123456 ``` 2. 创建多个数据源的配置类,分别注入不同的数据源连接信息,例如: ``` @Configuration public class PrimaryDataSourceConfig { @Bean(name = "primaryDataSource") @Primary @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } } @Configuration public class SecondaryDataSourceConfig { @Bean(name = "secondaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } } ``` 3. 在需要使用的地方注入对应的数据源,例如: ``` @Service public class UserService { @Autowired @Qualifier("primaryDataSource") private DataSource primaryDataSource; @Autowired @Qualifier("secondaryDataSource") private DataSource secondaryDataSource; // ... } ``` 通过以上步骤,就可以实现 Spring Boot 多数据源配置。 ### 回答2: Spring Boot是一个快速开发框架,其简便的配置方法吸引了越来越多的开发人员。在开发应用过程中,经常需要配置多个数据源以进行不同类型的数据操作。本文将介绍如何在Spring Boot中实现多数据源配置。 1. 添加依赖项 在pom.xml中添加以下依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 创建数据源配置类 我们可以通过编写一个配置类来声明不同的数据源。Spring Boot已经提供了DataSourceBuilder类来帮助我们创建数据源,它支持多种数据源类型,比如HikariCP,Tomcat JDBC等。以下是一个简单的数据源配置类的示例: ``` @Configuration public class DataSourceConfig { @Bean(name = "dataSource1") @ConfigurationProperties("spring.datasource.dataSource1") public DataSource dataSource1() { return DataSourceBuilder.create().type(HikariDataSource.class).build(); } @Bean(name = "dataSource2") @ConfigurationProperties("spring.datasource.dataSource2") public DataSource dataSource2() { return DataSourceBuilder.create().type(HikariDataSource.class).build(); } } ``` 请注意,我们通过使用@ConfigurationProperties注解将属性文件中的相关配置与Bean进行了绑定。 3. 配置JPA 如果您需要使用JPA来访问数据库,您需要在您的配置文件中配置JPA属性: ``` spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect ``` 4. 配置事务管理器 由于我们将使用多个数据源,因此需要一个事务管理器来控制跨多个数据源的事务。我们可以使用Spring Boot的PlatformTransactionManager来实现这一点。以下是一个简单的事务管理器配置: ``` @Configuration @EnableTransactionManagement public class TransactionConfig { @Autowired @Qualifier("dataSource1") private DataSource dataSource1; @Autowired @Qualifier("dataSource2") private DataSource dataSource2; @Bean(name = "transactionManager1") public PlatformTransactionManager transactionManager1() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory1().getObject()); transactionManager.setDataSource(dataSource1); return transactionManager; } @Bean(name = "transactionManager2") public PlatformTransactionManager transactionManager2() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory2().getObject()); transactionManager.setDataSource(dataSource2); return transactionManager; } @Bean(name = "entityManagerFactory1") public LocalContainerEntityManagerFactoryBean entityManagerFactory1() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource1); em.setPackagesToScan("com.example.entity1"); em.setPersistenceUnitName("dataSource1"); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); HashMap<String, Object> properties = new HashMap<>(); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); properties.put("hibernate.show_sql", true); em.setJpaPropertyMap(properties); return em; } @Bean(name = "entityManagerFactory2") public LocalContainerEntityManagerFactoryBean entityManagerFactory2() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource2); em.setPackagesToScan("com.example.entity2"); em.setPersistenceUnitName("dataSource2"); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); HashMap<String, Object> properties = new HashMap<>(); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); properties.put("hibernate.show_sql", true); em.setJpaPropertyMap(properties); return em; } } ``` 请注意,我们在此处使用了两个JpaTransactionManager Bean和两个LocalContainerEntityManagerFactoryBean Bean。我们使用@Qualifier注解明确表示了我们是使用哪个数据源配置的事务管理器或者实体管理器工厂Bean。 5. 配置数据库操作模板 最后一步是创建数据库操作模板,它可以使我们在实现数据库访问时更容易。同样,我们需要声明两个不同的模板,每个模板都使用不同的数据源: ``` @Configuration public class JdbcTemplateConfig { @Autowired @Qualifier("dataSource1") private DataSource dataSource1; @Autowired @Qualifier("dataSource2") private DataSource dataSource2; @Bean(name = "jdbcTemplate1") public JdbcTemplate jdbcTemplate1() { return new JdbcTemplate(dataSource1); } @Bean(name = "jdbcTemplate2") public JdbcTemplate jdbcTemplate2() { return new JdbcTemplate(dataSource2); } } ``` 到这里,我们已经完成了Spring Boot多数据源配置。我们可以使用这些数据源来访问不同的数据库,并使用声明的模板来执行数据库操作。这种方法可以更好地控制事务和并发,并提高应用的可伸缩性。 ### 回答3: 在实际开发中,我们常常需要使用多个数据源来实现数据的存储和读取。而Spring Boot框架提供了很方便的方式来配置多数据源Spring Boot支持使用两种方式来配置多数据源:使用Spring Boot自带的多数据源配置和手动配置多数据源。 使用Spring Boot自带的多数据源配置 Spring Boot已经为我们提供了一种默认的多数据源配置方式,我们只需要在application.properties或application.yml中指定多个数据源的配置信息即可。 以application.properties文件中配置MySQL和Oracle数据库为例: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test1 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.secondary.url=jdbc:oracle:thin:@localhost:1521:orcl spring.datasource.secondary.username=system spring.datasource.secondary.password=123456 spring.datasource.secondary.driver-class-name=oracle.jdbc.driver.OracleDriver ``` 在该示例中,我们定义了两个数据源:一个为MySQL,一个为Oracle。每个数据源有自己的配置信息,如url、username、password以及驱动等,这里省略了其他的配置项。 使用时我们只需要在代码中使用@Qualifier注解指定使用的数据源即可。 手动配置多数据源 如果我们需要更精细的控制多个数据源,我们可以手动配置多数据源。具体实现过程如下: 1.定义多个数据源配置信息类 我们可以创建多个数据源配置信息类,分别对应不同的数据源。每个类中包括了该数据源的一些配置信息,例如url、用户名、密码等。 示例代码: ``` @Configuration @MapperScan(basePackages = "com.example.demo.mapper.mysql", sqlSessionTemplateRef = "test1SqlSessionTemplate") public class Test1DataSourceConfig { @Bean(name = "test1DataSource") @ConfigurationProperties(prefix = "spring.datasource.test1") public DataSource test1DataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "test1SqlSessionFactory") public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "test1TransactionManager") public DataSourceTransactionManager test1TransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "test1SqlSessionTemplate") public SqlSessionTemplate test1SqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 示例代码中,我们使用@Configuration注解声明该类为配置类。同时我们使用@MapperScan注解声明了该数据源对应的Mapper类路径以及使用的SqlSessionTemplate,其中test1对应了我们之前定义的一个数据源。 在该类中,我们分别定义了该数据源对应的DataSource、SqlSessionFactory、DataSourceTransactionManager和SqlSessionTemplate。 2.配置多数据源 在上一步中,我们分别定义了多个数据源,下一步是将它们集成到一起。 Spring Boot提供了一个DynamicDataSource类,可以动态的创建数据源和切换数据源。我们可以在其中定义应用中所使用的所有数据源信息。 示例代码: ``` @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "dynamicDataSource") public DataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DatabaseType.MASTER, masterDataSource); targetDataSources.put(DatabaseType.SLAVE, slaveDataSource); MyRoutingDataSource dataSource = new MyRoutingDataSource(); dataSource.setDefaultTargetDataSource(masterDataSource); dataSource.setTargetDataSources(targetDataSources); return dataSource; } } ``` 我们在该类中分别定义了两个数据源masterDataSource和slaveDataSource,并通过注解@ConfigurationProperties(prefix="...")来指定相关的配置信息。 在dynamicDataSource方法中创建了一个MyRoutingDataSource对象,并以masterDataSource作为默认数据源。同时将所有数据源,即masterDataSource和slaveDataSource都添加到了一个HashMap中,并调用setTargetDataSources()方法设置到MyRoutingDataSource对象中。此时,我们就完成了对于多数据源的一个完整配置。 在访问数据库时,我们仍然可以像上一种方式那样,使用@Qualifier注解来指定使用哪个数据源: ``` public interface UserMapper { //使用test1数据源查询 @Select("SELECT * FROM user") @ResultType(User.class) @DataSourceType(MyContextHolder.DatabaseType.MYSQL) List<User> selectAll(); //使用test2数据源查询 @DataSourceType(MyContextHolder.DatabaseType.ORACLE) List<User> selectAll2(); } ``` 总结 Spring Boot实现多数据源的方式有两种,一种是使用Spring Boot自带的多数据源配置,另一种是手动配置多数据源。不管使用哪种方式,记得在使用时需要指定使用哪个具体的数据源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值