关于“SpringBoot集成多数据源解析”的完整攻略,我会进行如下的讲解:
一、前置知识
在了解“SpringBoot集成多数据源解析”之前,需要你掌握以下的技术:
- SpringBoot
- SpringDataJPA
- 数据源的概念
二、什么是多数据源
“多数据源”是指在一个应用程序中使用多个数据库连接。
在一个应用程序中,不同的业务功能可能需要操作不同的数据库,而不同的数据库可能具有不同的性质,如MySQL和Oracle的差异就很大。因此,为了保证应用程序的可扩展性和灵活性,就需要在同一个应用程序中集成多个数据源,以满足不同的业务需求。
三、如何实现多数据源
实现多数据源的方法很多,下面我们来介绍两种:
3.1、使用SpringBoot和SpringDataJPA集成多数据源
操作步骤:
- 1.在pom.xml中添加两个数据库连接的依赖类库:
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
- 2.定义数据源(dataSource)和JdbcTemplate:
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
- 3.在application.yml文件中配置数据源信息:
spring:
datasource:
primary:
jdbc-url: jdbc:mysql://10.30.10.149:3306/db_test?useUnicode=true&characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
hikari:
maximum-pool-size: 10
secondary:
jdbc-url: jdbc:oracle:thin:@127.0.0.1:1521:ORCL
driver-class-name: oracle.jdbc.OracleDriver
username: system
password: oracle
hikari:
maximum-pool-size: 10
- 4.编写测试代码:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
@Qualifier("primaryJdbcTemplate")
protected JdbcTemplate jdbcTemplate1;
@Autowired
@Qualifier("secondaryJdbcTemplate")
protected JdbcTemplate jdbcTemplate2;
@Test
public void test() throws Exception {
jdbcTemplate1.update("insert into user(id,name,age) values(?, ?, ?)", 1, "aaa", 20);
jdbcTemplate2.update("insert into user(id,name,age) values(?, ?, ?)", 1, "bbb", 30);
List<User> users1 = jdbcTemplate1.query("select * from user", new BeanPropertyRowMapper<>(User.class));
List<User> users2 = jdbcTemplate2.query("select * from user", new BeanPropertyRowMapper<>(User.class));
System.out.println("aaa:"+users1.size());
System.out.println("bbb:"+users2.size());
}
}
3.2、使用MyBatis Plus集成多数据源
操作步骤:
- 1.在pom.xml中添加以下依赖类库:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
- 2.在配置文件application.yml中配置不同数据源:
spring:
datasource:
# 主数据源
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
# 从数据源
slave:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
- 3.创建多数据源配置类:
@Configuration
public class DataSourceConfig {
/**
* 数据源1
*/
@Bean(name = "masterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
return new HikariDataSource();
}
/**
* 数据源2
*/
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slaveDataSource() {
return new HikariDataSource();
}
}
- 4.创建数据源和MyBatis SqlSessionFactory的配置类:
@Configuration
@MapperScan(basePackages = {"com.example.demo.mapper.slave"}, sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class SlaveDataSourceConfig {
@Autowired
@Qualifier("slaveDataSource")
private DataSource slaveDataSource;
@Bean(name = "slaveSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(slaveDataSource); // 使用从数据源
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml"));
return factoryBean.getObject();
}
@Bean(name = "slaveSqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
- 5.使用多数据源测试:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MultiDataSourceTest {
@Autowired
private UserService userService;
@Test
public void testInsert() {
User user = new User();
user.setUsername("test");
user.setPassword("test");
userService.save(user);
}
@Test
public void testSelect() {
userService.list().forEach(System.out::println);
}
}
四、总结
本文介绍了两种实现SpringBoot集成多数据源的方法,并分别给出了示例代码,希望对大家有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot集成多数据源解析 - Python技术站