溫馨提示×

springboot怎么連接多個數(shù)據(jù)源

小億
108
2023-12-08 15:57:58
欄目: 編程語言

在Spring Boot中連接多個數(shù)據(jù)源,可以使用Spring框架提供的多數(shù)據(jù)源支持。下面是一個示例:

  1. 配置多個數(shù)據(jù)源的連接信息。在application.properties(或application.yml)中配置多個數(shù)據(jù)源的連接信息,例如:
# 數(shù)據(jù)源1
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=root
spring.datasource.password=123456

# 數(shù)據(jù)源2
datasource2.url=jdbc:mysql://localhost:3306/db2
datasource2.username=root
datasource2.password=123456
  1. 創(chuàng)建多個數(shù)據(jù)源的配置類。分別創(chuàng)建多個配置類用于配置不同的數(shù)據(jù)源,例如:
@Configuration
public class DataSource1Config {
    
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }
}

@Configuration
public class DataSource2Config {
    
    @Bean
    @ConfigurationProperties(prefix = "datasource2")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }
}
  1. 創(chuàng)建多個數(shù)據(jù)源的JdbcTemplate實例。在需要使用數(shù)據(jù)源的地方,使用@Autowired注解注入對應的數(shù)據(jù)源,并創(chuàng)建JdbcTemplate實例,例如:
@RestController
public class UserController {
    
    @Autowired
    private DataSource dataSource1;
    
    @Autowired
    private DataSource dataSource2;
    
    @Bean
    public JdbcTemplate jdbcTemplate1() {
        return new JdbcTemplate(dataSource1);
    }
    
    @Bean
    public JdbcTemplate jdbcTemplate2() {
        return new JdbcTemplate(dataSource2);
    }
    
    @GetMapping("/users")
    public List<User> getUsers() {
        // 使用jdbcTemplate1查詢數(shù)據(jù)源1的用戶數(shù)據(jù)
        List<User> users1 = jdbcTemplate1().query("SELECT * FROM users", new BeanPropertyRowMapper<>(User.class));
        
        // 使用jdbcTemplate2查詢數(shù)據(jù)源2的用戶數(shù)據(jù)
        List<User> users2 = jdbcTemplate2().query("SELECT * FROM users", new BeanPropertyRowMapper<>(User.class));
        
        // 合并兩個數(shù)據(jù)源的用戶數(shù)據(jù)
        List<User> allUsers = new ArrayList<>();
        allUsers.addAll(users1);
        allUsers.addAll(users2);
        
        return allUsers;
    }
}

這樣,就可以使用多個數(shù)據(jù)源來連接不同的數(shù)據(jù)庫。在需要使用數(shù)據(jù)源的地方,可以根據(jù)具體的需求選擇對應的數(shù)據(jù)源進行操作。

0