springboot多数据源配置示例
时间: 2023-06-02 22:05:15 浏览: 97
好的,以下是一个简单的Spring Boot多数据源配置示例:
1.首先需要在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.3.1</version>
</dependency>
```
2.在application.properties文件中配置数据源及相关属性:
```properties
# 主数据源
spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.primary.username=root
spring.datasource.primary.password=password
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.primary.hikari.connectionTimeout=20000
spring.datasource.primary.hikari.maximumPoolSize=30
spring.datasource.primary.hikari.minimumIdle=10
# 第二个数据源
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.secondary.username=root
spring.datasource.secondary.password=password
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.secondary.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.secondary.hikari.connectionTimeout=20000
spring.datasource.secondary.hikari.maximumPoolSize=30
spring.datasource.secondary.hikari.minimumIdle=10
```
3.在代码中配置多数据源:
```java
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
```
4.在需要使用多数据源的Service类上添加@Qualifier注解,指定具体使用哪个数据源:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
}
```
以上就是一个简单的Spring Boot多数据源配置示例,希望能够帮助您。
阅读全文