SpringAOP implements annotation-based data source dynamic switching and springaop Annotation

Source: Internet
Author: User

SpringAOP implements annotation-based data source dynamic switching and springaop Annotation
Requirement

Code to implement read/write database Separation

Weapons

Spring3.0 or later

Implementation

1. inherit from org. springframework. jdbc. datasource. lookup. AbstractRoutingDataSource and customize data source routing.

2. implement data source type management tools, such as DBContextHolder, including setting and reading the current data source configuration.

3. Implement AOP for data source switching.

4. Custom read-only annotations, such as @ ReadOnlyKey.

5. Configure transactionManager to implement aop.

Sample Code

1. Custom DynamicDataSource

Public class DynamicDataSource extends actroutingdatasource {/*** automatically finds the data source ** @ return data source name */@ Override protected Object determineCurrentLookupKey () {String dataSource = getDataSource (); return dataSource ;}}

2. Data Source Type management tool DBContextHolder

Public abstract class DBContextHolder {/*** data source type management ** <p> * multiple threads are considered. To ensure that threads do not interfere with each other, ThreadLocal is used for thread isolation; <br> * the parameter is the data source key value * </p> ** @ see ThreadLocal */private static ThreadLocal <String> contextHolder = new ThreadLocal <String> (); /*** database Source Type ** <p> * When configuring the data source, observe the following constraints: <br> * read/write: performancekeyrw; <br> * read: performancekeyr. * </p> */public enum DbType {DB_TYPE_RW ("dataSourceKeyRW"), DB_TYPE_R ("dataSourceKeyR"); private String dataSourceKey; DbType (String cecekey) {this. performancekey = performancekey;} public String getperformancekey () {return performancekey;}/*** obtain the data source ** <p> * if not set, the read data source is returned by default * </p> ** @ return data source key value */public static String getDataSource () {String dataSource = contextHolder. get (); if (StringUtils. isEmpty (dataSource) {dataSource = DbType. DB_TYPE_RW.dataSourceKey;} return dataSource;}/*** Set Data Source ** @ param dataSourceKey data source key value */public static void setDataSource (String dataSourceKey) {contextHolder. set (performancekey );}}

Note: The DbType enumeration is defined, and the read and write data source key values are defined respectively.

3. Implement AOP.

Public class cesceswitchingaop {/*** set the cut-point data source * <p> * debug the output data source. * </p> ** @ param joinPoint cut point * @ param dataSourceKey current data source key value */private void setDataSourceByKey (JoinPoint joinPoint, String dataSourceKey) {setDataSource (dataSourceKey ); debugLog (joinPoint. getTarget (). getClass (). getSimpleName () + ". "+ joinPoint. getSignature (). getName () + "Configure Data source:" + getDataSource ();}/***** switch data source * <p> * Switch priority from The height is as follows; the method is annotated with performancekey, the method is annotated with ReadOnlyKey, and the class is annotated with performancekey; <br> * if not annotated, the data source is set by default. * </p> ** @ param joinPoint cut point * @ see DataSourceKey * @ see ReadOnlyKey * @ see DbType */public void switchDataSource (JoinPoint joinPoint) {Class <?> TargetClass = joinPoint. getTarget (). getClass (); String methodName = joinPoint. getSignature (). getName (); Object [] args = joinPoint. getArgs (); performancekey = getAnnotationClassMethod (targetClass, methodName, performancekey. class, args); if (performancekey! = Null) {setDataSourceByKey (joinPoint, dataSourceKey. cecekey (); return;} ReadOnlyKey readOnlyKey = equals (targetClass, methodName, ReadOnlyKey. class, args); if (readOnlyKey! = Null) {setDataSourceByKey (joinPoint, DbType. DB_TYPE_R.getDataSourceKey (); return;} performancekey = (performancekey) targetClass. getAnnotation (performancekey. class); if (performancekey! = Null) {setDataSourceByKey (joinPoint, dataSourceKey. dataSourceKey (); return;} setDataSourceByKey (joinPoint, DbType. db_type_r1_getdatasourcekey ());}}

4. Custom read-only annotation, @ ReadOnlyKey

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface ReadOnlyKey {}

5. Configure transaction and AOP

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dynamicDataSource"/>    </bean>
<bean id="dataSourceSwitchingAop" class="com.xxx.common.framework2x.dao.DataSourceSwitchingAop"/>
<aop:config>        <aop:aspect id="dataSourceSwitching" ref="dataSourceSwitchingAop" order="0">            <aop:pointcut id="dataSourceSwitchingService"                          expression="execution(* com.xxx.manager..*.*(..))"/>            <aop:before method="switchDataSource" pointcut-ref="dataSourceSwitchingService"/>        </aop:aspect>    </aop:config>

The above completes the dynamic switching of read/write data sources based on annotations.

6. If you want to switch between multiple data sources, you can customize the annotation @ cecekey

@ Retention (RetentionPolicy. RUNTIME) @ Target ({ElementType. METHOD, ElementType. TYPE}) public @ interface performancekey {/*** configure the data source key value * <p> * default: dataSource. * </p> ** @ return key value */String performancekey () default "dataSource ";}

Add annotations to the interface methods.

Notes

1. The transaction for switching the data source must be executed before the database transaction is started. In the preceding code example, you must specify order When configuring aop (the smaller the value, the higher the execution speed)

<aop:config>        <aop:aspect id="dataSourceSwitching" ref="dataSourceSwitchingAop" order="0">            <aop:pointcut id="dataSourceSwitchingService"                          expression="execution(* com.xxx.manager..*.*(..))"/>            <aop:before method="switchDataSource" pointcut-ref="dataSourceSwitchingService"/>        </aop:aspect>    </aop:config>

2. @ cecekey can be added to method or class. The priority is method> class.

3. @ ReadOnlyKey can only be added to method.

4. @ cecekey and @ ReadOnlyKey can be mixed in a class. The priority is @ DatasourceKey> @ ReadOnlyKey of the method> class.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.