spring集成mybatis實現mysql讀寫分離

前言

       在網站的用戶達到必定規模後,數據庫由於負載壓力太高而成爲網站的瓶頸。幸運的是目前大部分的主流數據庫都提供主從熱備功能,經過配置兩臺數據庫主從關係,能夠將一臺數據庫的數據更新同步到另外一臺服務器上。網站利用數據庫的這一功能,實現數據庫讀寫分離,從而改善數據庫負載壓力。以下圖所示:html

 

 

  應用服務器在寫數據的時候,訪問主數據庫,主數據庫經過主從複製機制將數據更新同步到從數據庫,這樣當應用服務器讀數據的時候,就能夠經過從數據庫得到數據。爲了便於應用程序訪問讀寫分離後的數據庫,一般在應用服務器使用專門的數據庫訪問模塊,使數據庫讀寫分離對應用透明。java

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

       而本博客就是來實現「專門的數據庫訪問模塊」,使數據庫讀寫分離對應用透明。另外,mysql數據庫的主從複製能夠參考個人mysql5.7.18的安裝與主從複製。注意,數據庫實現了主從複製,才能作數據庫的讀寫分離,因此,沒有實現數據庫主從複製的記得先去實現數據庫的主從複製git

配置讀寫數據源(主從數據庫)

       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

    主、從數據庫的地址記得改爲本身的,帳號和密碼也須要改爲本身的;其餘配置項,你們能夠酌情自行設置github

       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);
}

注意點

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

       事務須要注意,儘可能保證在一個數據源上進行事務;redis

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

  項目完整工程github地址:https://github.com/youzhibing/maven-ssm-web,工程中實現了redis緩存,不去訪問:http://localhost:8080/maven-ssm-web/personController/showPerson是沒有問題的,固然你能夠redis服務搭建起來並集成進來;sql

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

參考

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

  Spring+MyBatis實現數據庫讀寫分離方案

相關文章
相關標籤/搜索