在MySQL和MariaDB的Spring Boot应用程序中配置多个数据源,可以按照以下步骤进行:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
# 第一个数据源
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=username1
spring.datasource.password=password1
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 第二个数据源
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=username2
spring.datasource.secondary.password=password2
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
@Configuration
public class JdbcTemplateConfig {
@Bean(name = "jdbcTemplate")
public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
return new JdbcTemplate(secondaryDataSource);
}
}
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("secondaryJdbcTemplate")
private JdbcTemplate secondaryJdbcTemplate;
public void queryData() {
String sql = "SELECT * FROM table";
List<Map<String, Object>> result1 = jdbcTemplate.queryForList(sql);
List<Map<String, Object>> result2 = secondaryJdbcTemplate.queryForList(sql);
// 处理查询结果
}
通过以上步骤,就可以在MySQL和MariaDB的Spring Boot应用程序中配置多个数据源,并使用它们进行数据库操作。请注意,以上示例中的配置和代码仅供参考,实际情况可能会根据具体需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云