spring中AOP方式實現動態切換資料來源

來源:互聯網
上載者:User
總述
項目中有時會遇到多資料來源的情況,即在一個service中操作兩個或兩個以上的資料庫,這時就需要及時而準確地實現資料來源的切換。
通常,可以設定預設資料來源,在service中需要切換資料來源的地方指定新的資料來源,這種方式雖然可行,但存在兩個劣勢:
(1)過多指定新資料來源的做法會影響代碼清晰度,降低代碼的可讀性;
(2)如果service已經開啟事務,則資料來源切換失敗。
除了上述方法,還可以通過spring的AOP動態切換資料來源。
配置多資料來源
此處案例在spring和mybatis整合的環境中予以說明。
1.在spring-datasource.xml中配置多個資料來源
<!-- firstDataSource --><bean id="firstDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><property name="url" value="${firstDatasource.url}" /><property name="username" value="${firstDatasource.name}" /><property name="password" value="${firstDatasource.password}" /><property name="filters" value="log4j" /><property name="maxActive" value="${firstDatasource.maxActive}" /><property name="initialSize" value="${firstDatasource.initialiSize}" /><property name="maxWait" value="60000" /><property name="minIdle" value="1" /><property name="timeBetweenEvictionRunsMillis" value="3000" /><property name="minEvictableIdleTimeMillis" value="300000" /><property name="validationQuery" value="SELECT 'x'" /><property name="testWhileIdle" value="true" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /><property name="poolPreparedStatements" value="false" /><property name="maxPoolPreparedStatementPerConnectionSize" value="20" /></bean><!-- secondDataSource --><bean id="secondDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><property name="url" value="${secondDatasource.url}" /><property name="username" value="${secondDatasource.name}" /><property name="password" value="${secondDatasource.password}" /><property name="filters" value="log4j" /><property name="maxActive" value="${secondDatasource.maxActive}" /><property name="initialSize" value="${secondDatasource.initialiSize}" /><property name="maxWait" value="60000" /><property name="minIdle" value="1" /><property name="timeBetweenEvictionRunsMillis" value="3000" /><property name="minEvictableIdleTimeMillis" value="300000" /><property name="validationQuery" value="SELECT 'x'" /><property name="testWhileIdle" value="true" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /><property name="poolPreparedStatements" value="false" /><property name="maxPoolPreparedStatementPerConnectionSize" value="20" /></bean>
2.建立類DatabaseContextHolder,指定預設資料來源為firstDataSource
public class DatabaseContextHolder {private static final ThreadLocal<String> DATASOURCE_TYPE = new ThreadLocal<String>() {@Overrideprotected String initialValue() {return "firstDataSource";}};public static void setDbType(String dataSourceType) {DATASOURCE_TYPE.set(dataSourceType);}public static String getDbType() {return DATASOURCE_TYPE.get();}}
3.建立一個繼承AbstractRoutingDataSource的類DynamicDataSource,並實現determineCurrentLookupKey方法
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DatabaseContextHolder.getDbType();}}
4.在spring-datasource.xml中配置資料來源,class屬性值為上一步中所建立的類DynamicDataSource的路徑
<bean id="dataSource" class="cn.test.model.common.datasource.DynamicDataSource"><property name="defaultTargetDataSource" ref="firstDataSource" /><property name="targetDataSources"><map key-type="java.lang.String"><entry key="firstDataSource" value-ref="firstDataSource" /><entry key="secondDataSource" value-ref="secondDataSource" /></map></property></bean>
5.建立類DataSourceInterceptor,並於spring設定檔中增加AOP配置:<aop:aspectj-autoproxy expose-proxy="true"/>
import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;@Aspect@Component@Order(0)public class DataSourceInterceptor {@Pointcut("execution(* cn.test.model..service.impl.*FirstServiceImpl.*(..))")public void firstDataSource() {};@Pointcut("execution(* cn.test.model..service.impl.*SecondServiceImpl.*(..))")public void secondDataSource() {};@Before("firstDataSource()")public void beforeFirst(JoinPoint jp) {DatabaseContextHolder.setDbType("firstDataSource");}@Before("secondDataSource()")public void beforeSecond(JoinPoint jp) {DatabaseContextHolder.setDbType("secondDataSource");}}
配置事務
把事務配置在service的實作類別上
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><tx:annotation-driven /><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="find*" propagation="REQUIRED" read-only="true" /><tx:method name="query*" propagation="REQUIRED" read-only="true" /><tx:method name="list*" propagation="REQUIRED" read-only="true" /><tx:method name="search*" propagation="REQUIRED" read-only="true" /><tx:method name="get*" propagation="REQUIRED" read-only="true" /><tx:method name="save*" propagation="REQUIRED" /><tx:method name="add*" propagation="REQUIRED" /><tx:method name="update*" propagation="REQUIRED" /><tx:method name="delete*" propagation="REQUIRED" /><tx:method name="create*" propagation="REQUIRED" /><tx:method name="check*" propagation="REQUIRED" /><tx:method name="sync*" propagation="REQUIRED" /><tx:method name="execute*" propagation="REQUIRED" /><tx:method name="*" propagation="SUPPORTS" /></tx:attributes></tx:advice><aop:config><aop:pointcut id="interceptorPointCuts" expression="execution(* cn.test.model..service.impl.*ServiceImpl.*(..))" /><aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" order="1" /></aop:config>
資料來源的切換和事務的開啟都通過AOP來實現,二者的切點盡量配置在同一層級(類)上;需要注意的是,資料來源的切換必須先於事務的開啟。
注意事項
代碼採用servic間相互調用的方式。當*FirstServiceImpl中的某個方法saveData()調用*SecondService的方法時,首先被切換資料來源的切面攔截修改資料來源,然後開啟事務。
這時可能會出現的問題是,當*SecondService的方法執行完回到*FirstServiceImpl時,如果*FirstServiceImpl接下來還需要繼續操作firstDataSource,資料來源就會出現錯誤。這是因為此刻並未觸發修改資料來源的切面,資料來源仍然停留在secondDataSource,即使是調用*FirstServiceImpl本身的方法也是如此。
如何解決這個問題呢。可以把需要繼續執行的代碼拆出來放到一個新的service中,但這樣會破壞代碼的整體結構;更好的辦法是把後續代碼提取為*FirstService的一個介面,並在*FirstServiceImpl中實現,然後使用org.springframework.aop.framework.AopContext在*FirstServiceImpl中調用該介面,形如:
((DataFirstService)AopContext.currentProxy()).updateData();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.