有人看了我前面的两篇文章,说比较模糊,还是没有搞清具体的用法,希望我能在详细的完成一个案例,于是本文便出现了。本文在前面两篇《Spring 动态路由 AbstractRoutingDataSource(数据源动态切换)教程》、《详解 AbstractRoutingDataSource(动态数据源切换)实现原理》的基础上,通过一个读写分离的案例来进一步说明 AbstractRoutingDataSource 的用法。
更多精彩内容请看 web 前端中文站
http://www.lisa33xiaoq.net 可按 Ctrl + D 进行收藏
看下面的相关数据源切换配置:
<context:annotation-config /> <aop:aspectj-autoproxy /> <context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <context:property-placeholder location="classpath:com/resources/datasource.properties" /> <bean id="dataSourceRead" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${mysql.jdbc.driverClass}" /> <property name="jdbcUrl" value="${mysql.jdbc.url}" /> <property name="user" value="${mysql.jdbc.user}" /> <property name="password" value="${mysql.jdbc.password}" /> <property name="initialPoolSize" value="${mysql.jdbc.initialPoolSize}" /> <property name="minPoolSize" value="${mysql.jdbc.minPoolSize}" /> <property name="maxPoolSize" value="${mysql.jdbc.maxPoolSize}" /> <property name="checkoutTimeout" value="${mysql.jdbc.checkoutTimeout}" /> <property name="idleConnectionTestPeriod" value="${mysql.jdbc.idleConnectionTestPeriod}" /> <property name="maxIdleTime" value="${mysql.jdbc.maxIdleTime}" /> <property name="maxStatements" value="${mysql.jdbc.maxStatements}" /> <property name="testConnectionOnCheckout" value="${mysql.jdbc.testConnectionOnCheckout}" /> </bean> <bean id="dataSourceWrite" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${mysql.jdbc.driverClass}" /> <property name="jdbcUrl" value="${mysql.jdbc.url}" /> <property name="user" value="${mysql.jdbc.user}" /> <property name="password" value="${mysql.jdbc.password}" /> <property name="initialPoolSize" value="${mysql.jdbc.initialPoolSize}" /> <property name="minPoolSize" value="${mysql.jdbc.minPoolSize}" /> <property name="maxPoolSize" value="${mysql.jdbc.maxPoolSize}" /> <property name="checkoutTimeout" value="${mysql.jdbc.checkoutTimeout}" /> <property name="idleConnectionTestPeriod" value="${mysql.jdbc.idleConnectionTestPeriod}" /> <property name="maxIdleTime" value="${mysql.jdbc.maxIdleTime}" /> <property name="maxStatements" value="${mysql.jdbc.maxStatements}" /> <property name="testConnectionOnCheckout" value="${mysql.jdbc.testConnectionOnCheckout}" /> </bean> <bean id="dataSource" class="com.lisa33xiaoq.net.core.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="read" value-ref="dataSourceRead" /> <entry key="write" value-ref="dataSourceWrite" /> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceRead" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:com/resources/hibernate.cfg.xml" /> <property name="packagesToScan"> <list> <value>com.lisa33xiaoq.net.pojo</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <aop:config> <aop:pointcut id="serviceMethods" expression="execution(* com.lisa33xiaoq.net.service..*.*(..))" /> <aop:advisor advice-ref="txadvice" pointcut-ref="serviceMethods" /> </aop:config> <tx:advice id="txadvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="get*" read-only="true" propagation="SUPPORTS" /> <tx:method name="find*" read-only="true" propagation="SUPPORTS" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <bean id="dataSourceInterceptor" class="com.lisa33xiaoq.net.DataSourceInterceptor" /> <aop:config> <aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor"> <aop:pointcut id="read" expression="execution(* com.controller.read.*.*(..))" /> <aop:pointcut id="write" expression="execution(* com.controller.write.*.*(..))" /> <aop:before method="setdataSourceRead" pointcut-ref="read"/> <aop:before method="setdataSourceWrite" pointcut-ref="write"/> </aop:aspect> </aop:config>
动态数据源切换类实现代码如下:
package com.lisa33xiaoq.net.core; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { return DatabaseContextHolder.getCustomerType(); } }
DatabaseContextHolder 类型的实现代码如下:
package com.lisa33xiaoq.net.core; 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(); } }
下面是 DataSourceInterceptor 的实现代码:
package com.lisa33xiaoq.net.core; import org.aspectj.lang.JoinPoint; import org.springframework.stereotype.Component; @Component public class DataSourceInterceptor { public void setdataSourceRead(JoinPoint jp) { DatabaseContextHolder.setCustomerType("read"); } public void setdataSourceWrite(JoinPoint jp) { DatabaseContextHolder.setCustomerType("write"); } }
实体类就省略不写了,下面看看 read 包中的业务代码:
@Repository public class BrandDaoImpl implements IBrandDao { @Resource protected SessionFactory sessionFactory; @SuppressWarnings("unchecked") @Override public List<Brand> findAll() { String hql = "from Brand"; Query query = sessionFactory.getCurrentSession().createQuery(hql); return query.list(); } }
下面是 write 的包的实现:
@Repository public class CityDaoImpl implements ICityDao { @Resource private SessionFactory sessionFactory; @SuppressWarnings("unchecked") @Override public boolean save(List<City>) { .... } }
全部代码已经完毕了。但是上面的代码中有点缺陷,那就是把读和写分成两个 dao 了。这不是我们想要的。为此我又重新新做了一个 demo,限于篇幅,我就不贴代码了。新 demo 我已上传到了百度网盘链接:http://pan.baidu.com/s/1b68mIU 密码:otjz 欢迎下载。
本文原文出处:web 前端中文站: » Spring 读写分离多数据源配置教程
【注:本文源自网络文章资源,由站长整理发布】