天天看點

spring內建mybatis實作mysql讀寫分離

前言

       在網站的使用者達到一定規模後,資料庫因為負載壓力過高而成為網站的瓶頸。幸運的是目前大部分的主流資料庫都提供主從熱備功能,通過配置兩台資料庫主從關系,可以将一台資料庫的資料更新同步到另一台伺服器上。網站利用資料庫的這一功能,實作資料庫讀寫分離,進而改善資料庫負載壓力。如下圖所示:

spring內建mybatis實作mysql讀寫分離

  應用伺服器在寫資料的時候,通路主資料庫,主資料庫通過主從複制機制将資料更新同步到從資料庫,這樣當應用伺服器讀資料的時候,就可以通過從資料庫獲得資料。為了便于應用程式通路讀寫分離後的資料庫,通常在應用伺服器使用專門的資料庫通路子產品,使資料庫讀寫分離對應用透明。

摘自《大型網站技術架構_核心原理與案例分析》

       而本部落格就是來實作“專門的資料庫通路子產品”,使資料庫讀寫分離對應用透明。另外,mysql資料庫的主從複制可以參考我的mysql5.7.18的安裝與主從複制。注意,資料庫實作了主從複制,才能做資料庫的讀寫分離,是以,沒有實作資料庫主從複制的記得先去實作資料庫的主從複制

配置讀寫資料源(主從資料庫)

       mysqldb.properties

#主資料庫資料源
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.0.4:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=123456
jdbc.initialSize=1
jdbc.minIdle=1
jdbc.maxActive=20
jdbc.maxWait=60000
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=180
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=SELECT 1
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false

#從資料庫資料源
slave.jdbc.driverClassName=com.mysql.jdbc.Driver
slave.jdbc.url=jdbc:mysql://192.168.0.221:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false
slave.jdbc.username=root
slave.jdbc.password=123456
slave.jdbc.initialSize=1
slave.jdbc.minIdle=1
slave.jdbc.maxActive=20
slave.jdbc.maxWait=60000
slave.jdbc.removeAbandoned=true
slave.jdbc.removeAbandonedTimeout=180
slave.jdbc.timeBetweenEvictionRunsMillis=60000
slave.jdbc.minEvictableIdleTimeMillis=300000
slave.jdbc.validationQuery=SELECT 1
slave.jdbc.testWhileIdle=true
slave.jdbc.testOnBorrow=false
slave.jdbc.testOnReturn=false      

    主、從資料庫的位址記得改成自己的,賬号和密碼也需要改成自己的;其他配置項,大家可以酌情自行設定

       mybatis-spring.xml

<?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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- master資料源 -->
    <bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 基本屬性 url、user、password -->  
        <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="initialSize" value="${jdbc.initialSize}" />  
        <property name="minIdle" value="${jdbc.minIdle}" />   
        <property name="maxActive" value="${jdbc.maxActive}" />  
        <property name="maxWait" value="${jdbc.maxWait}" />
        <!-- 超過時間限制是否回收 -->
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
        <!-- 超過時間限制多長; -->
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接配接,機關是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一個連接配接在池中最小生存的時間,機關是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
        <!-- 用來檢測連接配接是否有效的sql,要求是一個查詢語句-->
        <property name="validationQuery" value="${jdbc.validationQuery}" />
        <!-- 申請連接配接的時候檢測 -->
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
        <!-- 申請連接配接時執行validationQuery檢測連接配接是否有效,配置為true會降低性能 -->
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
        <!-- 歸還連接配接時執行validationQuery檢測連接配接是否有效,配置為true會降低性能  -->
        <property name="testOnReturn" value="${jdbc.testOnReturn}" />
    </bean>

    <!-- slave資料源 -->
    <bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${slave.jdbc.driverClassName}" />  
        <property name="url" value="${slave.jdbc.url}" />  
        <property name="username" value="${slave.jdbc.username}" />  
        <property name="password" value="${slave.jdbc.password}" />  
        <property name="initialSize" value="${slave.jdbc.initialSize}" />  
        <property name="minIdle" value="${slave.jdbc.minIdle}" />   
        <property name="maxActive" value="${slave.jdbc.maxActive}" />  
        <property name="maxWait" value="${slave.jdbc.maxWait}" />
        <property name="removeAbandoned" value="${slave.jdbc.removeAbandoned}" />
        <property name="removeAbandonedTimeout" value="${slave.jdbc.removeAbandonedTimeout}" />
        <property name="timeBetweenEvictionRunsMillis" value="${slave.jdbc.timeBetweenEvictionRunsMillis}" />
        <property name="minEvictableIdleTimeMillis" value="${slave.jdbc.minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="${slave.jdbc.validationQuery}" />
        <property name="testWhileIdle" value="${slave.jdbc.testWhileIdle}" />
        <property name="testOnBorrow" value="${slave.jdbc.testOnBorrow}" />
        <property name="testOnReturn" value="${slave.jdbc.testOnReturn}" />
    </bean>
    
    <!-- 動态資料源,根據service接口上的注解來決定取哪個資料源 -->
    <bean id="dataSource" class="com.yzb.util.DynamicDataSource">  
        <property name="targetDataSources">      
          <map key-type="java.lang.String">      
              <!-- write or slave -->    
             <entry key="slave" value-ref="slaveDataSource"/>      
             <!-- read or master   -->  
             <entry key="master" value-ref="masterDataSource"/>      
          </map>               
        </property>   
        <property name="defaultTargetDataSource" ref="masterDataSource"/>      
      
    </bean>
    
    <!-- Mybatis檔案 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml" /> 
        <property name="dataSource" ref="dataSource" />
        <!-- 映射檔案路徑 -->
        <property name="mapperLocations" value="classpath*:dbmappers/*.xml" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yzb.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 聲明式開啟 -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" order="1"/>
    
    <!-- 為業務邏輯層的方法解析@DataSource注解  為目前線程的HandleDataSource注入資料源 -->    
    <bean id="dataSourceAspect" class="com.yzb.util.DataSourceAspect" />    
    <aop:config proxy-target-class="true">    
        <aop:aspect id="dataSourceAspect" ref="dataSourceAspect" order="2">    
            <aop:pointcut id="tx" expression="execution(* com.yzb.service.impl..*.*(..)) "/>    
            <aop:before pointcut-ref="tx" method="before" />                
        </aop:aspect>    
    </aop:config>
</beans>      

AOP實作資料源的動态切換

DataSource.java

package com.yzb.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**  
 * RUNTIME  
 * 編譯器将把注釋記錄在類檔案中,在運作時 VM 将保留注釋,是以可以反射性地讀取。  
 *  
 */  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD) 
public @interface DataSource
{
    String value();
}      

DataSourceAspect.java

package com.yzb.util;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

public class DataSourceAspect
{
    /**
     * 在dao層方法擷取datasource對象之前,在切面中指定目前線程資料源
     */
    public void before(JoinPoint point)
    {

        Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?>[] classz = target.getClass().getInterfaces();                        // 擷取目标類的接口, 是以@DataSource需要寫在接口上
        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);
                System.out.println("使用者選擇資料庫庫類型:" + data.value());
                HandleDataSource.putDataSource(data.value());                        // 資料源放到目前線程中
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    }      

DynamicDataSource.java

package com.yzb.util;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource
{

    /**
     * 擷取與資料源相關的key 此key是Map<String,DataSource> resolvedDataSources 中與資料源綁定的key值
     * 在通過determineTargetDataSource擷取目标資料源時使用
     */
    @Override
    protected Object determineCurrentLookupKey()
    {
        return HandleDataSource.getDataSource();
    }

}      

HandleDataSource.java

package com.yzb.util;

public class HandleDataSource
{
    public static final ThreadLocal<String> holder = new ThreadLocal<String>();

    /**
     * 綁定目前線程資料源
     * 
     * @param key
     */
    public static void putDataSource(String datasource)
    {
        holder.set(datasource);
    }

    /**
     * 擷取目前線程的資料源
     * 
     * @return
     */
    public static String getDataSource()
    {
        return holder.get();
    }
}      

service接口上應用@DataSource實作資料源的指定

package com.yzb.service;

import java.util.List;

import com.yzb.model.Person;
import com.yzb.util.DataSource;

public interface IPersonService {

    /**
     * 加載全部的person
     * @return
     */
    List<Person> listAllPerson();
    
    /**
     * 查詢某個人的資訊
     * @param personId
     * @return
     */
    @DataSource("slave")            // 指定使用從資料源
    Person getPerson(int personId);
    
    boolean updatePerson(Person person);
}      

注意點

  測試的時候,怎麼樣知道讀取的是從資料庫了? 我們可以修改從資料庫中查詢到的那條記錄的某個字段的值,以區分主、從資料庫;

       事務需要注意,盡量保證在一個資料源上進行事務;

       當某個service上有多個aop時,需要注意aop織入的順序問題,利用order關鍵字控制好織入順序;

  項目完整工程github位址:https://github.com/youzhibing/maven-ssm-web,工程中實作了redis緩存,不去通路:http://localhost:8080/maven-ssm-web/personController/showPerson是沒有問題的,當然你可以redis服務搭建起來并內建進來;

  測試url:http://localhost:8080/maven-ssm-web/personController/person?personId=1

參考

  《大型網站技術架構_核心原理與案例分析》

  Spring+MyBatis實作資料庫讀寫分離方案