Spring通过xml配置动态切换数据源

实现原理

1.扩展Spring的抽象类AbstractRoutingDataSource(该类充当了DataSource的路由中介,在运行时,能根据某key值来动态切换到真正的DataSource上),重写determineCurrentLookupkey()抽象方法。determineCurrentLookupkey()方法的返回值是我们所要用到的DataSource的key值,有了这个key值,我们就可以从map(该map的key和value值是在配置文件中配置好存入的)中取出对应的DataSource,如果找不到,就用默认数据源。

2.编写数据源操作类的接口,设置默认数据源为null,因为当程序没有找到关联的数据源时,就会调用默认数据源

 
  1. package com.shadow.system.base.source;

  2.  
  3. import org.aspectj.lang.JoinPoint;

  4.  
  5. /**

  6. * 数据源切换接口

  7. *

  8. * @author shadow

  9. * @create 2013.04.03

  10. */

  11. public interface DataSourceEntry {

  12.  
  13. // 默认数据源

  14. public final static String DEFAULT_SOURCE = null;

  15.  
  16. /**

  17. * 还原数据源

  18. *

  19. * @param joinPoint

  20. */

  21. public void restore(JoinPoint join);

  22.  
  23. /**

  24. * 设置数据源

  25. *

  26. * @param dataSource

  27. */

  28. public void set(String source);

  29.  
  30. /**

  31. * 获取数据源

  32. *

  33. * @return String

  34. */

  35. public String get();

  36.  
  37. /**

  38. * 清空数据源

  39. */

  40. public void clear();

  41. }


3.写个实现类,从当前线程取出数据源名

 
  1. package com.shadow.system.base.source;

  2.  
  3. import org.aspectj.lang.JoinPoint;

  4.  
  5. import com.shadow.system.dictionary.DynamicTypeEntry;

  6.  
  7. /**

  8. * 数据源切换实现类类

  9. *

  10. * @author shadow

  11. * @create 2013.04.03

  12. */

  13. public class DataSourceEntryImpl implements DynamicTypeEntry {

  14.  
  15. private final static ThreadLocal<String> local = new ThreadLocal<String>();

  16.  
  17. public void clear() {

  18. local.remove();

  19. }

  20.  
  21. public String get() {

  22. return local.get();

  23. }

  24.  
  25. public void restore(JoinPoint join) {

  26. local.set(DEFAULT_SOURCE); // 设置null数据源

  27. }

  28.  
  29. public void set(String source) {

  30. local.set(source);

  31. }

  32.  
  33. }


4.扩展AbstractRoutingDataSource类,并注入DataSourceEntry,重写里面的determineCurrentLookupkey()方法,实现动态切换数据源。

 
  1. package com.shadow.system.base.source;

  2.  
  3. import javax.annotation.Resource;

  4.  
  5. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

  6.  
  7. /**

  8. * 获取数据源(依赖SPRING框架)

  9. *

  10. * @author shadow

  11. * @create 2013.04.03

  12. */

  13. public class DynamicDataSource extends AbstractRoutingDataSource {

  14.  
  15. private DataSourceEntry dataSourceEntry;

  16.  
  17. @Override

  18. protected Object determineCurrentLookupKey() {

  19. return this.dataSourceEntry.get();

  20. }

  21.  
  22. @Resource

  23. public void setDataSourceEntry(DataSourceEntry dataSourceEntry) {

  24. this.dataSourceEntry = dataSourceEntry;

  25. }

  26.  
  27. }


5.最后就是配置.xml文件,以后只需要直接管理DynamicDataSource这个接口就可以了,至于它内部是使用的是哪个数据源是不需要关注的。写的切面还原是为了保证每次调用完另外的数据源都会还原成默认数据源,防止有的人忘记设置回默认的,导致其他代码出问题。项目中,为了精简,可以单独分离出来jdbc.xml数据源配置文件。

 
  1. <!-- JDBC模板 -->

  2. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

  3. <property name="dataSource" ref="dynamicDataSource" />

  4. </bean>

  5.  
  6. <!-- 获取数据源配置 -->

  7. <bean

  8. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

  9. <property name="locations">

  10. <value>classpath:properties/jdbc.properties</value>

  11. </property>

  12. </bean>

  13.  
  14. <!-- 配置动态数据源 -->

  15. <bean id="dynamicDataSource" class="com.shadow.system.base.source.DynamicDataSource">

  16. <!-- 通过key-value的形式来关联数据源 -->

  17. <property name="targetDataSources">

  18. <map key-type="java.lang.String">

  19. <entry value-ref="C3P0_COMMON" key="C3P0_COMMON"></entry>

  20. </map>

  21. </property>

  22. <property name="defaultTargetDataSource" ref="C3P0_COMMON" />

  23. </bean>

  24.  
  25. <!-- database config -->

  26. <bean id="C3P0_COMMON" class="com.mchange.v2.c3p0.ComboPooledDataSource"

  27. destroy-method="close" lazy-init="true">

  28. <property name="driverClass" value="${sqlite.driverClass}" />

  29. <property name="jdbcUrl" value="${sqlite.jdbcUrl}" />

  30. <property name="minPoolSize" value="${sqlite.miniPoolSize}" />

  31. <property name="maxPoolSize" value="${sqlite.maxPoolSize}" />

  32. <property name="initialPoolSize" value="${sqlite.initialPoolSize}" />

  33. <property name="maxIdleTime" value="${sqlite.maxIdleTime}" />

  34. <property name="acquireIncrement" value="${sqlite.acquireIncrement}" />

  35. <property name="acquireRetryAttempts" value="${sqlite.acquireRetryAttempts}" />

  36. <property name="acquireRetryDelay" value="${sqlite.acquireRetryDelay}" />

  37. <property name="testConnectionOnCheckin" value="${sqlite.testConnectionOnCheckin}" />

  38. <property name="testConnectionOnCheckout" value="${sqlite.testConnectionOnCheckout}" />

  39. <property name="autoCommitOnClose" value="${sqlite.autoCommitOnClose}" />

  40. <property name="idleConnectionTestPeriod" value="${sqlite.idleConnectionTestPeriod}" />

  41. <property name="checkoutTimeout" value="${sqlite.checkoutTimeout}" />

  42. <property name="numHelperThreads" value="${sqlite.numHelperThreads}" />

  43. </bean>

  44.  
  45. <!-- 配置数据源切换实现类 -->

  46. <bean id="dataSourceEntry" class="com.shadow.system.base.source.DataSourceEntryImpl" />

  47.  
  48. <!-- 切面还原默认数据源 -->

  49. <aop:config>

  50. <aop:aspect id="dataSourceHolderAdviceAspect" ref="dataSourceEntry">

  51. <aop:after method="restore"

  52. pointcut=<span><span class="string">"execution(* com.shadow.mvc.service.SmsService.saveOrderSMS(..))"</span><span></span></span> />

  53. </aop:aspect>

  54. </aop:config>


6.在程序中如何变换数据源,可以在切面中通过before,来检测切换数据源的方法。也可以在程序中直接使用DataSourceEntry的set方法。

 
  1. public List<Sms> findForAll() {

  2. dataSourceEntry.set(DynamicTypeEntry.C3P0_ACCESS);

  3. return this.smsDao.queryForAll();

  4. }

转载出处  :https://blog.csdn.net/licheng989/article/details/47623023

猜你喜欢

转载自blog.csdn.net/weixin_41558728/article/details/81082411