spring boot多数据源配置

[b][color=green]spring boot多数据源的配置,spring boot+mybatis配置数据源[/color][/b]

[color=green]第一步pom.xml配置如下:[/color]

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

<!-- Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- MYSQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>

</dependencies>


[color=green]第二步application.properties配置如下:[/color]
#datascore one
spring.datasource.primary.url=jdbc:mysql://localhost/testdb1
spring.datasource.primary.username=test1
spring.datasource.primary.password=1234
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver


#datascore two
spring.datasource.secondary.url=jdbc:mysql://localhost/testdb2
spring.datasource.secondary.username=test2
spring.datasource.secondary.password=1234
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver


[color=green]第三步主要数据源对象配置如下:[/color]
/**
* 数据源test1的配置
* @author zx
* @date 2017-03-12
*/
@Configuration
@MapperScan(basePackages = "com.zx.dao.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")
public class DataSource1Config {

@Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}

@Bean(name = "test1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/test1/*Mapper*.xml"));
return bean.getObject();
}

@Bean(name = "test1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}

@Bean(name = "test1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}

}


/**
* 数据源test2的配置
* @author zx
* @date 2017-03-12
*/
@Configuration
@MapperScan(basePackages = "com.zx.dao.test2", sqlSessionTemplateRef = "test2SqlSessionTemplate")
public class DataSource2Config {

@Bean(name = "test2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}

@Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/test2/*.xml"));
return bean.getObject();
}

@Bean(name = "test2TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}

@Bean(name = "test2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}

}


[color=red]具体项目参考github如下:[/color]
[color=green]项目地址:[url]https://github.com/zhangxia1030/spring-boot-datasources[/url][/color]
  • 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、付费专栏及课程。

余额充值