动态数据源配置

在使用dubbo作为分布式服务治理框架时,遇到了一个问题,像优惠码这样的大批量数据查询和导出接口,是不适合提供dubbo服务的。

所以要讲优惠码查询接口迁移到cms里来。这样的话需要配置两个数据源,具体做法如下:

一、配置多数据源:

<!-- DBCP数据源配置 -->
    <bean id="komectbackend" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="url" value="${jdbc.komectbackend.url}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="username" value="${jdbc.komectbackend.username}" />
        <property name="password" value="${jdbc.komectbackend.password}" />

        <!-- 超过即回收,默认值:8 -->
        <property name="maxIdle" value="20"/>
        <!-- minIdle要与timeBetweenEvictionRunsMillis配合使用才有用,单独使用minIdle不会起作用.默认值:0-->
        <property name="minIdle" value="5"/>
        <property name="initialSize" value="5"/>

        <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->
        <property name="testOnBorrow" value="false"/>
        <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能  -->
        <property name="testOnReturn" value="false"/>
        <!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于
             timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。  -->
        <property name="testWhileIdle" value="true"/>
        <!-- 每60秒运行一次空闲连接回收器 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 用来检测连接是否有效的sql,要求是一个查询语句,如果validationQuery为
             null,testOnBorrow、testOnReturn、testWhileIdle都不起其作用。 -->
        <property name="validationQuery" value="select user()"/>
    </bean>
     <!-- DBCP数据源配置 -->
    <bean id="komecthealth" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="url" value="${jdbc.komecthealth.url}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="username" value="${jdbc.komecthealth.username}" />
        <property name="password" value="${jdbc.komecthealth.password}" />

        <!-- 超过即回收,默认值:8 -->
        <property name="maxIdle" value="20"/>
        <!-- minIdle要与timeBetweenEvictionRunsMillis配合使用才有用,单独使用minIdle不会起作用.默认值:0-->
        <property name="minIdle" value="5"/>
        <property name="initialSize" value="5"/>

        <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->
        <property name="testOnBorrow" value="false"/>
        <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能  -->
        <property name="testOnReturn" value="false"/>
        <!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于
             timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。  -->
        <property name="testWhileIdle" value="true"/>
        <!-- 每60秒运行一次空闲连接回收器 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 用来检测连接是否有效的sql,要求是一个查询语句,如果validationQuery为
             null,testOnBorrow、testOnReturn、testWhileIdle都不起其作用。 -->
        <property name="validationQuery" value="select user()"/>
    </bean>
    <bean id="dynamicDataSource" class="com.cmcc.komectcms.common.util.DynamicDataSource" >  
	    <!-- 通过key-value的形式来关联数据源 -->  
	    <property name="targetDataSources">  
	        <map>  
	            <entry value-ref="komectbackend" key="komectbackend"></entry>
	            <entry value-ref="komecthealth" key="komecthealth"></entry>
	        </map>  
	    </property>  
	    <property name="defaultTargetDataSource" ref="komectbackend" />
	</bean>  
    
	<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dynamicDataSource" />
        <property name="configLocation" value="classpath:mybatis.xml" />
        <property name="mapperLocations" value="classpath*:sqlmap/**/*.xml" />
		<property name="plugins">
			<bean
				class="com.cmcc.akso.plugin.database.page.PaginationInterceptor">
				<property name="properties">
					<props>
						<prop key="dialect">${jdbc.type}</prop>
        			</props>
				</property>
			</bean>
		</property>
    </bean>
     <!-- mybatis mapper scan -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cmcc.komectcms.dao" />
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
    </bean>
    
    <!-- 事务管理器配置,多数据源事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dynamicDataSource" />
    </bean>
    <aop:config>
		<aop:aspect id="dsAspect" ref="dataSourceInterceptor">
			<aop:pointcut id="dskommecthealth" expression="execution(* com.cmcc.komectcms.dao.coupon..*(..))" />
			<aop:before method="setKomecthealth" pointcut-ref="dskommecthealth"/>
		</aop:aspect>
	</aop:config>
    <!-- 使用annotation定义事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

二、因为cms配置了komectend默认为数据源,这里只需将komecthealth作为备用的数据源,拦截优惠券相关接口,使用该数据源,配置拦截器如上

 

三、配置好sqlSessionFactory和事务管理器

四、添加相应的拦截器DataSourceInterceptor,并声明为spring组件

@Component
public class DataSourceInterceptor {

	public void setKomectbackend(JoinPoint jp) {
		DatabaseContextHolder.setCustomerType("komectbackend");
	}
	
	public void setKomecthealth(JoinPoint jp) {
		DatabaseContextHolder.setCustomerType("komecthealth");
	}
}

拦截器的方法名要与配置中的一致,在dao.coupon包下的文件执行之前加入切面dsAspect,设置切点为dskomecthealth,即数据源为komecthealth。

 

五、添加一个线程池:

public class DatabaseContextHolder {

	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

	public static void setCustomerType(String customerType) {
		contextHolder.set(customerType);
	}

	public static String getCustomerType() {
		return contextHolder.get();
	}

	public static void clearCustomerType() {
		contextHolder.remove();
	}
}
public class DynamicDataSource extends AbstractRoutingDataSource{

	@Override
	protected Object determineCurrentLookupKey() {
		return DatabaseContextHolder.getCustomerType(); 
	}

}

 

该功能提交一段时间后,居然诡异的在网站上出现了错误代码,说是调不到komecthealth.t_sys_users等表,经排查将aop切点修改为如下就好了,可能是这样更精确点吧

 

 

<aop:pointcut id="dskommecthealth" expression="execution(* com.cmcc.komectcms.dao.coupon.CouponCmmsDao.*(..))" />  

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot支持动态数据源配置,可以根据需要动态地切换数据源。以下是动态数据源配置的步骤: 1. 在pom.xml文件中添加依赖: ```xml <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> ``` 2. 配置数据源,在application.properties文件中添加以下配置: ```properties spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.hikari.jdbc-url=jdbc:mysql://localhost:3306/db?characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.hikari.username=root spring.datasource.hikari.password=123456 ``` 3. 创建多个数据源,在配置类中添加以下配置: ```java @Configuration public class DataSourceConfig { @Bean(name = "dataSource1") @ConfigurationProperties(prefix = "spring.datasource.hikari.datasource1") public DataSource dataSource1() { return DataSourceBuilder.create().type(HikariDataSource.class).build(); } @Bean(name = "dataSource2") @ConfigurationProperties(prefix = "spring.datasource.hikari.datasource2") public DataSource dataSource2() { return DataSourceBuilder.create().type(HikariDataSource.class).build(); } } ``` 4. 创建动态数据源,在配置类中添加以下配置: ```java @Configuration public class DynamicDataSourceConfig { @Bean(name = "dynamicDataSource") public DynamicDataSource dynamicDataSource(@Qualifier("dataSource1") DataSource dataSource1, @Qualifier("dataSource2") DataSource dataSource2) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("dataSource1", dataSource1); targetDataSources.put("dataSource2", dataSource2); return new DynamicDataSource(dataSource1, targetDataSources); } } ``` 5. 创建动态数据源切换类,在配置类中添加以下配置: ```java public class DynamicDataSource extends AbstractRoutingDataSource { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultTargetDataSource); super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override protected Object determineCurrentLookupKey() { return contextHolder.get(); } public static void setDataSource(String dataSource) { contextHolder.set(dataSource); } public static void clearDataSource() { contextHolder.remove(); } } ``` 6. 在需要切换数据源的地方,调用DynamicDataSource.setDataSource("dataSource1")或DynamicDataSource.setDataSource("dataSource2")方法切换数据源。 以上就是Spring Boot动态数据源配置的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值