如今大型的電子商務系統,在數據庫層面大都採用讀寫分離技術,就是一個Master數據庫,多個Slave數據庫。Master庫負責數據更新和實時數據查詢,Slave庫固然負責非實時數據查詢。由於在實際的應用中,數據庫都是讀多寫少(讀取數據的頻率高,更新數據的頻率相對較少),而讀取數據一般耗時比較長,佔用數據庫服務器的CPU較多,從而影響用戶體驗。咱們一般的作法就是把查詢從主庫中抽取出來,採用多個從庫,使用負載均衡,減輕每一個從庫的查詢壓力。html
採用讀寫分離技術的目標:有效減輕Master庫的壓力,又能夠把用戶查詢數據的請求分發到不一樣的Slave庫,從而保證系統的健壯性。咱們看下采用讀寫分離的背景。java
隨着網站的業務不斷擴展,數據不斷增長,用戶愈來愈多,數據庫的壓力也就愈來愈大,採用傳統的方式,好比:數據庫或者SQL的優化基本已達不到要求,這個時候能夠採用讀寫分離的策 略來改變現狀。web
具體到開發中,如何方便的實現讀寫分離呢?目前經常使用的有兩種方式:spring
1 第一種方式是咱們最經常使用的方式,就是定義2個數據庫鏈接,一個是MasterDataSource,另外一個是SlaveDataSource。更新數據時咱們讀取MasterDataSource,查詢數據時咱們讀取SlaveDataSource。這種方式很簡單,我就不贅述了。sql
2 第二種方式動態數據源切換,就是在程序運行時,把數據源動態織入到程序中,從而選擇讀取主庫仍是從庫。主要使用的技術是:annotation,Spring AOP ,反射。下面會詳細的介紹實現方式。數據庫
在介紹實現方式以前,咱們先準備一些必要的知識,spring 的AbstractRoutingDataSource 類express
AbstractRoutingDataSource這個類 是spring2.0之後增長的,咱們先來看下AbstractRoutingDataSource的定義:服務器
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {}mybatis
AbstractRoutingDataSource繼承了AbstractDataSource ,而AbstractDataSource 又是DataSource 的子類。DataSource 是javax.sql 的數據源接口,定義以下:app
public interface DataSource extends CommonDataSource,Wrapper { /** * <p>Attempts to establish a connection with the data source that * this <code>DataSource</code> object represents. * * @return a connection to the data source * @exception SQLException if a database access error occurs */ Connection getConnection() throws SQLException; /** * <p>Attempts to establish a connection with the data source that * this <code>DataSource</code> object represents. * * @param username the database user on whose behalf the connection is * being made * @param password the user's password * @return a connection to the data source * @exception SQLException if a database access error occurs * @since 1.4 */ Connection getConnection(String username, String password) throws SQLException; }
DataSource 接口定義了2個方法,都是獲取數據庫鏈接。咱們在看下AbstractRoutingDataSource 如何實現了DataSource接口:
public Connection getConnection() throws SQLException { return determineTargetDataSource().getConnection(); } public Connection getConnection(String username, String password) throws SQLException { return determineTargetDataSource().getConnection(username, password); }
很顯然就是調用本身的determineTargetDataSource() 方法獲取到connection。determineTargetDataSource方法定義以下:
protected DataSource determineTargetDataSource() { Assert.notNull(this.resolvedDataSources, "DataSource router not initialized"); 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; }
咱們最關心的仍是下面2句話:
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
determineCurrentLookupKey方法返回lookupKey,resolvedDataSources方法就是根據lookupKey從Map中得到數據源。resolvedDataSources 和determineCurrentLookupKey定義以下:
private Map<Object, DataSource> resolvedDataSources;
protected abstract Object determineCurrentLookupKey()
看到以上定義,咱們是否是有點思路了,resolvedDataSources是Map類型,咱們能夠把MasterDataSource和SlaveDataSource存到Map中,以下:
key value
master MasterDataSource
slave SlaveDataSource
咱們在寫一個類DynamicDataSource 繼承AbstractRoutingDataSource,實現其determineCurrentLookupKey() 方法,該方法返回Map的key,master或slave。
好了,說了這麼多,有點煩了,下面咱們看下怎麼實現。
上面已經提到了咱們要使用的技術,咱們先看下annotation的定義:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DataSource { String value(); }
咱們還須要實現spring的抽象類AbstractRoutingDataSource,就是實現determineCurrentLookupKey方法:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { return DynamicDataSourceHolder.getDataSouce(); } }
public class DynamicDataSourceHolder { public static final ThreadLocal<String> holder = new ThreadLocal<String>(); public static void putDataSource(String name) { holder.set(name); } public static String getDataSouce() { return holder.get(); } }
從DynamicDataSource 的定義看出,他返回的是DynamicDataSourceHolder.getDataSouce()值,咱們須要在程序運行時調用DynamicDataSourceHolder.putDataSource()方法,對其賦值。下面是咱們實現的核心部分,也就是AOP部分,DataSourceAspect定義以下:
public class DataSourceAspect { public void before(JoinPoint point) { Object target = point.getTarget(); String method = point.getSignature().getName(); Class<?>[] classz = target.getClass().getInterfaces(); Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()) .getMethod().getParameterTypes(); try { Method m = classz[0].getMethod(method, parameterTypes); if (m != null && m.isAnnotationPresent(DataSource.class)) { DataSource data = m .getAnnotation(DataSource.class); DynamicDataSourceHolder.putDataSource(data.value()); System.out.println(data.value()); } } catch (Exception e) { // TODO: handle exception } } }
public class DataSourceType { /** master **/ public static final String MASTER = "master"; /** slave **/ public static final String SLAVE = "slave"; }
爲了方便測試,我定義了2個數據庫,表結構一致,但數據不一樣,數據庫配置以下:
<!-- 配置數據源 第一數據源(寫庫) --> <bean name="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${jdbc.validationQuery}" /> <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> <property name="testOnReturn" value="${jdbc.testOnReturn}" /> <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> <property name="filters" value="${jdbc.filters}" /> <!-- 關閉abanded鏈接時輸出錯誤日誌 --> <property name="logAbandoned" value="true" /> <property name="proxyFilters"> <list> <ref bean="log-filter"/> </list> </property> </bean> <!-- 配置數據源 第二數據源(讀庫) --> <bean name="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${slave.jdbc.url}" /> <property name="username" value="${slave.jdbc.username}" /> <property name="password" value="${slave.jdbc.password}" /> </bean> <bean id="dataSource" class="com.abc.cc.web.common.core.source.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <!-- write --> <entry key="master" value-ref="masterDataSource"/> <!-- read --> <entry key="slave" value-ref="slaveDataSource"/> </map> </property> <property name="defaultTargetDataSource" ref="masterDataSource"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations"> <list> <value>classpath:com/abc/cc/web/*/*/mapper/*.xml</value> </list> </property> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <bean id="baseMybatisDao" class="com.qdingnet.pcloud.resource.common.dao.BaseMybatisDao" > <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.abc.cc.web.*.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置數據庫註解aop --> <aop:aspectj-autoproxy /> <bean id="manyDataSourceAspect" class="com.qdingnet.pcloud.resource.common.core.source.DataSourceAspect"/> <aop:config> <aop:aspect id="c" ref="manyDataSourceAspect"> <aop:pointcut id="tx" expression="execution(* com.abc.cc.web.*.dao.*.*(..))"/> <aop:before pointcut-ref="tx" method="before"/> </aop:aspect> </aop:config>
下面是MyBatis的mapper的定義,讀的都是slave:
@DataSource(DataSourceType.SLAVE) List<RemindInfo> getRemindListByUserId(@Param("userId")String userId,@Param("pageIndex")Integer pageIndex,@Param("pageSize")Integer pageSize); @DataSource(DataSourceType.SLAVE) Integer getRemindCountByUserId(@Param("userId")String userId);
轉載,原文地址:http://www.cnblogs.com/surge/p/3582248.html