一聚教程网:一个值得你收藏的教程网站

热门教程

Spring如何实现数据库读写分离的教程

时间:2022-06-29 07:49:25 编辑:袖梨 来源:一聚教程网

现在大型的电子商务系统,在数据库层面大都采用读写分离技术,就是一个Master数据库,多个Slave数据库。Master库负责数据更新和实时数据查询,Slave库当然负责非实时数据查询。因为在实际的应用中,数据库都是读多写少(读取数据的频率高,更新数据的频率相对较少),而读取数据通常耗时比较长,占用数据库服务器的CPU较多,从而影响用户体验。我们通常的做法就是把查询从主库中抽取出来,采用多个从库,使用负载均衡,减轻每个从库的查询压力。

采用读写分离技术的目标:有效减轻Master库的压力,又可以把用户查询数据的请求分发到不同的Slave库,从而保证系统的健壮性。我们看下采用读写分离的背景。

随着网站的业务不断扩展,数据不断增加,用户越来越多,数据库的压力也就越来越大,采用传统的方式,比如:数据库或者SQL的优化基本已达不到要求,这个时候可以采用读写分离的策 略来改变现状。

具体到开发中,如何方便的实现读写分离呢?目前常用的有两种方式:

1 第一种方式是我们最常用的方式,就是定义2个数据库连接,一个是MasterDataSource,另一个是SlaveDataSource。更新数据时我们读取MasterDataSource,查询数据时我们读取SlaveDataSource。这种方式很简单,我就不赘述了。

2 第二种方式动态数据源切换,就是在程序运行时,把数据源动态织入到程序中,从而选择读取主库还是从库。主要使用的技术是:annotation,Spring AOP ,反射。下面会详细的介绍实现方式。

在介绍实现方式之前,我们先准备一些必要的知识,spring 的AbstractRoutingDataSource 类

AbstractRoutingDataSource这个类 是spring2.0以后增加的,我们先来看下AbstractRoutingDataSource的定义:

复制代码代码如下:

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {}

AbstractRoutingDataSource继承了AbstractDataSource ,而AbstractDataSource 又是DataSource 的子类。DataSource 是javax.sql 的数据源接口,定义如下:

publicinterfaceDataSourceextendsCommonDataSource,Wrapper {
 
 /**
  *

Attempts to establish a connection with the data source that

  * this DataSource object represents.
  *
  * @return a connection to the data source
  * @exception SQLException if a database access error occurs
  */
 Connection getConnection()throwsSQLException;
 
 /**
  *

Attempts to establish a connection with the data source that

  * this DataSource 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)
  throwsSQLException;
 
}

DataSource 接口定义了2个方法,都是获取数据库连接。我们在看下AbstractRoutingDataSource 如何实现了DataSource接口:

publicConnection getConnection()throwsSQLException {
    returndetermineTargetDataSource().getConnection();
  }
 
  publicConnection getConnection(String username, String password)throwsSQLException {
    returndetermineTargetDataSource().getConnection(username, password);
  }

很显然就是调用自己的determineTargetDataSource() 方法获取到connection。determineTargetDataSource方法定义如下:

protectedDataSource 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) {
      thrownewIllegalStateException("Cannot determine target DataSource for lookup key ["+ lookupKey +"]");
    }
    returndataSource;
  }

我们最关心的还是下面2句话:

Object lookupKey = determineCurrentLookupKey();
DataSource dataSource =this.resolvedDataSources.get(lookupKey);

determineCurrentLookupKey方法返回lookupKey,resolvedDataSources方法就是根据lookupKey从Map中获得数据源。resolvedDataSources 和determineCurrentLookupKey定义如下:

privateMap resolvedDataSources;
 
protectedabstractObject determineCurrentLookupKey()

看到以上定义,我们是不是有点思路了,resolvedDataSources是Map类型,我们可以把MasterDataSource和SlaveDataSource存到Map中,如下:

key  value
master MasterDataSource
slave SlaveDataSource

我们在写一个类DynamicDataSource 继承AbstractRoutingDataSource,实现其determineCurrentLookupKey() 方法,该方法返回Map的key,master或slave。

好了,说了这么多,有点烦了,下面我们看下怎么实现。

上面已经提到了我们要使用的技术,我们先看下annotation的定义:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public@interfaceDataSource {
  String value();
}

我们还需要实现spring的抽象类AbstractRoutingDataSource,就是实现determineCurrentLookupKey方法:

publicclassDynamicDataSourceextendsAbstractRoutingDataSource {
 
  @Override
  protectedObject determineCurrentLookupKey() {
    // TODO Auto-generated method stub
    returnDynamicDataSourceHolder.getDataSouce();
  }
 
}
 
 
publicclassDynamicDataSourceHolder {
  publicstaticfinalThreadLocal holder =newThreadLocal();
 
  publicstaticvoidputDataSource(String name) {
    holder.set(name);
  }
 
  publicstaticString getDataSouce() {
    returnholder.get();
  }
}

从DynamicDataSource 的定义看出,他返回的是DynamicDataSourceHolder.getDataSouce()值,我们需要在程序运行时调用DynamicDataSourceHolder.putDataSource()方法,对其赋值。下面是我们实现的核心部分,也就是AOP部分,DataSourceAspect定义如下:

publicclassDataSourceAspect {
 
  publicvoidbefore(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
    }
  }
}

为了方便测试,我定义了2个数据库,shop模拟Master库,test模拟Slave库,shop和test的表结构一致,但数据不同,数据库配置如下:

    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    
    
    
    
  
 
  
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    
    
    
    
  
   
    
    
       
         
         
         
         
       
        
    
    
  
 
  
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    
  
 
 
  
  
    
    
  

在spring的配置中增加aop配置

  
  
  
    
      
      
    
  
  

下面是MyBatis的UserMapper的定义,为了方便测试,登录读取的是Master库,用户列表读取Slave库:

publicinterfaceUserMapper {
  @DataSource("master")
  publicvoidadd(User user);
 
  @DataSource("master")
  publicvoidupdate(User user);
 
  @DataSource("master")
  publicvoiddelete(intid);
 
  @DataSource("slave")
  publicUser loadbyid(intid);
 
  @DataSource("master")
  publicUser loadbyname(String name);
   
  @DataSource("slave")
  publicList list();
} 

好了,运行我们的Eclipse看看效果,输入用户名admin 登录看看效果

热门栏目