如今大型的电子商务系统,在数据库层面大都采用读写分离技术,就是一个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