<转>Spring AOP根据JdbcTemplate方法名动态设置数据源

本文介绍如何在Spring框架中通过AOP技术实现多数据源的动态切换,包括配置不同数据源、根据方法名自动选择合适的数据源进行读写操作,并通过自定义拦截器实现数据源的动态设置。

转载: Spring AOP根据JdbcTemplate方法名动态设置数据源

http://blog.youkuaiyun.com/yubaoma2014/article/details/12427885
作者: yubaoma2014

 

有删节.

 

目的: 

1. 配置多个数据源

2. 根据不同的数据源执行不同的数据操作方法

3. 事务管理?

 

  • 多数据源配置
        <!-- 主数据源, 用于执行写入操作 -->
        <bean id="masterDataSource"
            class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <property name="driverClassName"
                value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <property name="poolPreparedStatements" value="true" />
            <property name="defaultAutoCommit" value="true" />
        </bean>
        <!-- 从数据源, 用于执行查询操作 -->
        <bean id="slaveDataSource"
            class="org.apache.commons.dbcp.BasicDataSource"
            destroy-method="close">
            <property name="driverClassName"
                value="${jdbc.driverClassName}" />
            <property name="url" value="${jdbc.url2}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <property name="poolPreparedStatements" value="true" />
            <property name="defaultAutoCommit" value="true" />
        </bean>
    
        <!-- 动态数据源 -->
        <bean id="dataSource"
            class="test.my.serivce.ds.DynamicDataSource">
            <!-- 配置一个数据源Map, 注意这里的key值, 后面很多地方都使用到 -->
            <property name="targetDataSources">
                <map>
                    <entry key="master" value-ref="masterDataSource" />
                    <entry key="slave" value-ref="slaveDataSource" />
                </map>
            </property>
            <!-- 动态数据源默认使用的数据源 -->
            <property name="defaultTargetDataSource" ref="masterDataSource" />
        </bean>
    
    <!-- 配置JdbcTemplate -->
    <bean id="jdbcTemplate"
            class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
    BEAN "dataSource" 是自定义类DynamicDataSource的一个实例, 而DynamicDataSource则是继承了Spring的抽象类AbstractRoutingDataSource, 顾名思义, 这是一个数据源的路由/查找类.
    import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    // 自定义类
    public class DynamicDataSource extends AbstractRoutingDataSource {
        
        @Override
        // 返回当前需要使用的数据源的key
        protected Object determineCurrentLookupKey() {
            // 
            return CustomerContextHolder.getCustomerType();
        }
    }
     
    //  AbstractRoutingDataSource 的部分源码
    
    public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
            
            // 重写了 getConnection() 方法
         	@Override
    	public Connection getConnection() throws SQLException {
    		return determineTargetDataSource().getConnection();
    	}
    
            // 设置当前使用的目标数据源
    	protected DataSource determineTargetDataSource() {
    		Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
                    // 目标数据源的key.
    		Object lookupKey = determineCurrentLookupKey();
                    // 获取数据源
    		DataSource dataSource = this.resolvedDataSources.get(lookupKey);
    		if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
    			dataSource = this.resolvedDefaultDataSource;
    		}
    		if (dataSource == null) {
    			throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
    		}
    		return dataSource;
    	}
            
            // 抽象方法, 返回目标数据源对应的key
            // 这里的key对应于在BEAN "dataSource"中配置的属性"targetDataSources"中的key
            protected abstract Object determineCurrentLookupKey();
    }
     
    // CustomerContextHolder, 一个ThreadLocal实现, 用于管理key
    // ThreadLocal是线程安全的, 且线程之间不能共享
    public class CustomerContextHolder {
        private static final ThreadLocal contextHolder = new ThreadLocal();
        public static void setCustomerType(String customerType) {
            contextHolder.set(customerType);
        }
        public static String getCustomerType() {
            return (String) contextHolder.get();
        }
        public static void clearCustomerType() {
            contextHolder.remove();
        }
    }
     
  • 利用AOP, 实现不同的数据源执行不同的数据操作方法
        <bean id="ba" class="test.my.serivce.ds.BeforeAdvice" />
        <!-- 强制使用CGLIB代理 -->
        <aop:config proxy-target-class="true">
    
            <!-- 切面一 主数据源执行写入操作 -->
            <aop:aspect ref="ba">
                <!-- 切点, 与数据库update相关的函数 -->
                <aop:pointcut id="update"
                    expression="execution(* org.springframework.jdbc.core.JdbcTemplate.update*(..)) || execution(* org.springframework.jdbc.core.JdbcTemplate.batchUpdate(..))" />
                <!-- 前置通知, 执行数据源设置操作 -->
                <aop:before method="setMasterDataSource"
                    pointcut-ref="update" />
            </aop:aspect>
    
            <!-- 切面二 从数据源执行查询操作 -->
            <aop:aspect ref="ba">
                <aop:before method="setSlaveDataSource"
                    pointcut="execution(* org.springframework.jdbc.core.JdbcTemplate.query*(..)) || execution(* org.springframework.jdbc.core.JdbcTemplate.execute(..))" />
            </aop:aspect>
        </aop:config>
        
     BEAN "ba"相关的类
    public class BeforeAdvice {
        public void setMasterDataSource() {
            CustomerContextHolder.setCustomerType("master");
        }
        public void setSlaveDataSource() {
            CustomerContextHolder.setCustomerType("slave");
        }
    }
     
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd"> <!-- 使用缓存annotation 配置 --> <!-- <cache:annotation-driven cache-manager="ehCacheManager" /> --> <mvc:default-servlet-handler/> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <bean id="masterSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName"> <value>${jdbc.driverClassName}</value> </property> <property name="url"> <value>${jdbc.url.master}</value> </property> <property name="username"> <value>${jdbc.username.master}</value> </property> <property name="password"> <value>${jdbc.password.master}</value> </property> <!-- 连接池最大使用连接数 --> <property name="maxActive"> <value>50</value> </property> <!-- 初始化连接大小 --> <property name="initialSize"> <value>1</value> </property> <!-- 获取连接最大等待间 --> <property name="maxWait"> <value>60000</value> </property> <!-- 连接池最大空闲 --> <!-- <property name="maxIdle"> <value>20</value> </property> --> <!-- 连接池最小空闲 --> <property name="minIdle"> <value>30</value> </property> <property name="testWhileIdle"> <value>true</value> </property> <property name="validationQuery"> <value>select 1 from dual</value> </property> <!-- 自动清除无用连接 --> <property name="removeAbandoned"> <value>true</value> </property> <!-- 清除无用连接的等待间 --> <property name="removeAbandonedTimeout"> <value>90</value> </property> <!-- 连接属性 --> <property name="connectionProperties"> <value>clientEncoding=UTF-8</value> </property> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis"> <value>60000</value> </property> <!-- 配置一个连接在池中最小生存的间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis"> <value>300000</value> </property> </bean> <bean id="slaveSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName"> <value>${jdbc.driverClassName}</value> </property> <property name="url"> <value>${jdbc.url.slave}</value> </property> <property name="username"> <value>${jdbc.username.slave}</value> </property> <property name="password"> <value>${jdbc.password.slave}</value> </property> <!-- 连接池最大使用连接数 --> <property name="maxActive"> <value>50</value> </property> <!-- 初始化连接大小 --> <property name="initialSize"> <value>1</value> </property> <!-- 获取连接最大等待间 --> <property name="maxWait"> <value>60000</value> </property> <!-- 连接池最大空闲 --> <!-- <property name="maxIdle"> <value>20</value> </property> --> <!-- 连接池最小空闲 --> <property name="minIdle"> <value>30</value> </property> <property name="testWhileIdle"> <value>true</value> </property> <property name="validationQuery"> <value>select 1 from dual</value> </property> <!-- 自动清除无用连接 --> <property name="removeAbandoned"> <value>true</value> </property> <!-- 清除无用连接的等待间 --> <property name="removeAbandonedTimeout"> <value>90</value> </property> <!-- 连接属性 --> <property name="connectionProperties"> <value>clientEncoding=UTF-8</value> </property> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis"> <value>60000</value> </property> <!-- 配置一个连接在池中最小生存的间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis"> <value>300000</value> </property> </bean> <bean id="dynamicDataSource" class="com.sjsemi.rrc.datasource.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="master" value-ref="masterSource"/> <entry key="slave" value-ref="slaveSource"/> </map> </property> <!-- 默认数据源 --> <property name="defaultTargetDataSource" ref="masterSource"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dynamicDataSource"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dynamicDataSource"/> <!-- 配置myBatis全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 扫描entity包 使用别名 --> <property name="typeAliasesPackage" value="com.sjsemi.rrc.entity"/> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath*:com/sjsemi/rrc/mybatis/**/*Mapper.xml"/> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helpDialect = oracle </value> </property> </bean> </array> </property> </bean> <context:component-scan base-package="com.sjsemi.rrc"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <task:annotation-driven scheduler="taskScheduler" mode="proxy"/> <task:scheduler id="taskScheduler" pool-size="10"/> <!-- 文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> </bean> <!-- 扫描basePackage下所有的接口类,根据对应的mapper.xml为其生成代理类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.sjsemi.rrc.mybatis.mapper"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg> </bean> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dynamicDataSource"></property> </bean> <!-- 注解方式配置事务 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/> <tx:method name="append*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="creat*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="modify*" propagation="REQUIRED"/> <tx:method name="edit*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED"/> <tx:method name="repair" propagation="REQUIRED"/> <tx:method name="delAndRepair" propagation="REQUIRED"/> <tx:method name="get*" read-only="true"/> <tx:method name="query*" read-only="true"/> <tx:method name="select*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="load*" read-only="true"/> <tx:method name="search*" read-only="true"/> <tx:method name="datagrid*" read-only="true"/> <tx:method name="*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.sjsemi.rrc.service.impl.*.*(..))"/> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/> </aop:config> <aop:aspectj-autoproxy proxy-target-class="true"/> <bean id="dataSourceAspect" class="com.sjsemi.rrc.datasource.DataSourceAspect"/> <aop:config> <aop:pointcut id="dataSourcePointcut" expression="execution(* com.sjsemi.rrc.service.impl.*.*(..))"/> <aop:advisor pointcut-ref="dataSourcePointcut" advice-ref="dataSourceAspect" order="1"/> </aop:config> </beans>
最新发布
10-11
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值