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

公司内部项目从SpringMVC转型至SpringBoot,期间遇到不少小挫折,现记录下来方便其他小伙伴能够少走坑。

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

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

1.在application-dev.properties中写入

#mysql x1
spring.datasource.url=xxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#mysql x2
spring.datasource-wmatch.url=xxx
spring.datasource-wmatch.username=xxx
spring.datasource-wmatch.password=xxx
spring.datasource-wmatch.driver-class-name=com.mysql.jdbc.Driver

#mysql x3
spring.datasource-match.url=xxx
spring.datasource-match.username=xxx
spring.datasource-match.password=xxx
spring.datasource-match.driver-class-name=com.mysql.jdbc.Driver
2.
@Configuration
// Springboot多数据源获取配置基类
public class DataSourceConfig {
	//get set 对应配置文件中的4个属性
	private String url;
	private String username;
	private String password;
	private String driverClassName;

	@Bean(name = "micDataSource")
	@Primary //主数据源
	@ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource")
	public DataSource micDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "wmatchDataSource")
	@ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource-wmatch")
	public DataSource wmatchDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "matchDataSource")
	@ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource-match")
	public DataSource matchDataSource() {
		return DataSourceBuilder.create().build();
	}
	

	//拿到不同数据源的SessionFactory
	@Bean(name = "micSessionFactory")
	@Primary
	public LocalSessionFactoryBean micSessionFactory(@Qualifier("micDataSource") DataSource dataSource) {
		LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
		bean.setDataSource(dataSource);
	    return bean;
	}

	@Bean(name = "wmatchSessionFactory")
	public LocalSessionFactoryBean wmatchSessionFactory(@Qualifier("wmatchDataSource") DataSource dataSource) {
		LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
		bean.setDataSource(dataSource);
	    return bean;
	}
	
	@Bean(name = "matchSessionFactory")
	public LocalSessionFactoryBean matchSessionFactory(@Qualifier("matchDataSource") DataSource dataSource) {
		LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
		bean.setDataSource(dataSource);
	    return bean;
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * @param url
	 *            the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username
	 *            the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the driverClassName
	 */
	public String getDriverClassName() {
		return driverClassName;
	}

	/**
	 * @param driverClassName
	 *            the driverClassName to set
	 */
	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}
}
以上配置已经结束,只需要在使用的地方进行针对不同SessionFactory的注入即可,注入关键字@Qualifier

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
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; } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菠萝-琪琪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值