SpringBoot 配置Mysql多数据源DataSource以及各种工作环境切换

通常我们一个项目可能存在开发、联调、测试、线上等环境,那么我们使用SpringBoot的工作环境切换配置会很方便,首先新建一个application-dev.properties开发环境文件,然后再application.properties主文件中使用spring.profiles.active=dev引入开发环境配置即可。

下面开始详解多数据源的配置:

1.在application-dev.properties中写入

 
  1. #mysql x1

  2. spring.datasource.url=xxx

  3. spring.datasource.username=xxx

  4. spring.datasource.password=xxx

  5. spring.datasource.driver-class-name=com.mysql.jdbc.Driver

  6.  
  7. #mysql x2

  8. spring.datasource-wmatch.url=xxx

  9. spring.datasource-wmatch.username=xxx

  10. spring.datasource-wmatch.password=xxx

  11. spring.datasource-wmatch.driver-class-name=com.mysql.jdbc.Driver

  12.  
  13. #mysql x3

  14. spring.datasource-match.url=xxx

  15. spring.datasource-match.username=xxx

  16. spring.datasource-match.password=xxx

  17. spring.datasource-match.driver-class-name=com.mysql.jdbc.Driver

2.

 
  1. @Configuration

  2. // Springboot多数据源获取配置基类

  3. public class DataSourceConfig {

 
  1. //get set 对应配置文件中的4个属性

  2. private String url;

  3. private String username;

  4. private String password;

  5. private String driverClassName;

  6.  
  7. @Bean(name = "micDataSource")

  8. @Primary //主数据源

  9. @ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource")

  10. public DataSource micDataSource() {

  11. return DataSourceBuilder.create().build();

  12. }

  13.  
  14. @Bean(name = "wmatchDataSource")

  15. @ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource-wmatch")

  16. public DataSource wmatchDataSource() {

  17. return DataSourceBuilder.create().build();

  18. }

  19.  
  20. @Bean(name = "matchDataSource")

  21. @ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource-match")

  22. public DataSource matchDataSource() {

  23. return DataSourceBuilder.create().build();

  24. }

  25.  
 
  1.  
  2.  
 
  1. //拿到不同数据源的SessionFactory

  2. @Bean(name = "micSessionFactory")

  3. @Primary

  4. public LocalSessionFactoryBean micSessionFactory(@Qualifier("micDataSource") DataSource dataSource) {

  5. LocalSessionFactoryBean bean = new LocalSessionFactoryBean();

  6. bean.setDataSource(dataSource);

  7. return bean;

  8. }

  9.  
  10. @Bean(name = "wmatchSessionFactory")

  11. public LocalSessionFactoryBean wmatchSessionFactory(@Qualifier("wmatchDataSource") DataSource dataSource) {

  12. LocalSessionFactoryBean bean = new LocalSessionFactoryBean();

  13. bean.setDataSource(dataSource);

  14. return bean;

  15. }

  16.  
  17. @Bean(name = "matchSessionFactory")

  18. public LocalSessionFactoryBean matchSessionFactory(@Qualifier("matchDataSource") DataSource dataSource) {

  19. LocalSessionFactoryBean bean = new LocalSessionFactoryBean();

  20. bean.setDataSource(dataSource);

  21. return bean;

  22. }

  23.  
  24. /**

  25. * @return the url

  26. */

  27. public String getUrl() {

  28. return url;

  29. }

  30.  
  31. /**

  32. * @param url

  33. * the url to set

  34. */

  35. public void setUrl(String url) {

  36. this.url = url;

  37. }

  38.  
  39. /**

  40. * @return the username

  41. */

  42. public String getUsername() {

  43. return username;

  44. }

  45.  
  46. /**

  47. * @param username

  48. * the username to set

  49. */

  50. public void setUsername(String username) {

  51. this.username = username;

  52. }

  53.  
  54. /**

  55. * @return the password

  56. */

  57. public String getPassword() {

  58. return password;

  59. }

  60.  
  61. /**

  62. * @param password

  63. * the password to set

  64. */

  65. public void setPassword(String password) {

  66. this.password = password;

  67. }

  68.  
  69. /**

  70. * @return the driverClassName

  71. */

  72. public String getDriverClassName() {

  73. return driverClassName;

  74. }

  75.  
  76. /**

  77. * @param driverClassName

  78. * the driverClassName to set

  79. */

  80. public void setDriverClassName(String driverClassName) {

  81. this.driverClassName = driverClassName;

  82. }

  83. }

以上配置已经结束,只需要在使用的地方进行针对不同SessionFactory的注入即可,注入关键字@Qualifier

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "localContainerEntityManagerFactoryBean" ,
        basePackages = "com.newframe.repositories.dataMaster",
        repositoryBaseClass = BaseRepositoryEx.class)
public class MasterRepositoryConfig {

    @Autowired
    @Qualifier("masterDataSource")
    private DataSource masterDS;

    @Autowired
    private JpaProperties jpaProperties;

    @Primary
    @Bean("entityManager")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder){
        return localContainerEntityManagerFactoryBean(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean("localContainerEntityManagerFactoryBean")
    public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean(EntityManagerFactoryBuilder entityManagerFactoryBuilder){
        return entityManagerFactoryBuilder.dataSource(masterDS)
                .properties(getProperties())
                .packages("com.newframe.entity")
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

    private Map<String, Object> getProperties(){
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot结合MyBatisPlus配置多数据源的示例代码主要包括以下几个步骤[^1][^2]: 1. **配置文件信息**: 在`application.properties`或`application.yml`中添加多数据源配置,例如: ```properties # 主数据源配置 spring.datasource.master.url=jdbc:mysql://localhost:3306/master_db spring.datasource.master.username=root spring.datasource.master.password=master_password # 备份数据源配置 spring.datasource_slave.url=jdbc:mysql://localhost:3306/backup_db spring.datasource_slave.username=root spring.datasource_slave.password=backup_password # 数据源切换相关配置 spring.aop.auto=true data-source-switch.datasource-names=master,slave ``` 2. **多数据源配置类**: 创建一个`DataSourceSwitch`配置类,通常会继承`AbstractRoutingDataSource`或自定义实现: ```java import org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException; import org.springframework.jdbc.datasource.lookup.DataSourceUtils; public class DataSourceSwitch extends AbstractRoutingDataSource { private String dataSourceName; @Override protected Object determineCurrentLookupKey() { return dataSourceName; } // 在需要切换数据源的地方调用此方法 public void switchDataSource(String dataSourceName) { this.dataSourceName = dataSourceName; try { setTargetDataSource(DataSourceUtils.getConnection(dataSourceName)); } catch (DataSourceLookupFailureException e) { throw new RuntimeException("切换数据源失败", e); } } } ``` 3. **动态数据源切换**: 使用Spring AOP在需要访问数据库的地方自动切换数据源,比如在Repository接口上添加切面: ```java @Aspect @Configuration public class DataSourcesAspect { @Autowired private DataSourceSwitch dataSourceSwitch; @Before("execution(* com.example.repository.*.*(..))") public void switchDataSource(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); String methodName = signature.getMethod().getName(); dataSourceSwitch.switchDataSource(methodName.equals("master") ? "master" : "slave"); } } ``` 4. **MyBatisPlus配合**: 在MyBatisPlus的全局配置类中,注入数据源,这样MyBatisPlus就会自动使用当前的数据源: ```java @Configuration public class GlobalConfig { @Autowired private DataSourceSwitch dataSourceSwitch; @Bean public GlobalConfig globalConfig() { GlobalConfig config = new GlobalConfig(); config.setDataSource(dataSourceSwitch.getTargetDataSource()); return config; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值