溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在spring中使用mybatis實現(xiàn)對mysql數(shù)據(jù)庫進行讀寫分離

發(fā)布時間:2020-12-01 16:56:51 來源:億速云 閱讀:286 作者:Leah 欄目:編程語言

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)在spring中使用mybatis實現(xiàn)對mysql數(shù)據(jù)庫進行讀寫分離,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

前言

       在網(wǎng)站的用戶達到一定規(guī)模后,數(shù)據(jù)庫因為負(fù)載壓力過高而成為網(wǎng)站的瓶頸。幸運的是目前大部分的主流數(shù)據(jù)庫都提供主從熱備功能,通過配置兩臺數(shù)據(jù)庫主從關(guān)系,可以將一臺數(shù)據(jù)庫的數(shù)據(jù)更新同步到另一臺服務(wù)器上。網(wǎng)站利用數(shù)據(jù)庫的這一功能,實現(xiàn)數(shù)據(jù)庫讀寫分離,從而改善數(shù)據(jù)庫負(fù)載壓力。如下圖所示:

在spring中使用mybatis實現(xiàn)對mysql數(shù)據(jù)庫進行讀寫分離

  應(yīng)用服務(wù)器在寫數(shù)據(jù)的時候,訪問主數(shù)據(jù)庫,主數(shù)據(jù)庫通過主從復(fù)制機制將數(shù)據(jù)更新同步到從數(shù)據(jù)庫,這樣當(dāng)應(yīng)用服務(wù)器讀數(shù)據(jù)的時候,就可以通過從數(shù)據(jù)庫獲得數(shù)據(jù)。為了便于應(yīng)用程序訪問讀寫分離后的數(shù)據(jù)庫,通常在應(yīng)用服務(wù)器使用專門的數(shù)據(jù)庫訪問模塊,使數(shù)據(jù)庫讀寫分離對應(yīng)用透明。

       而本博客就是來實現(xiàn)“專門的數(shù)據(jù)庫訪問模塊”,使數(shù)據(jù)庫讀寫分離對應(yīng)用透明。另外,mysql數(shù)據(jù)庫的主從復(fù)制可以參考我的mysql5.7.18的安裝與主從復(fù)制。注意,數(shù)據(jù)庫實現(xiàn)了主從復(fù)制,才能做數(shù)據(jù)庫的讀寫分離,所以,沒有實現(xiàn)數(shù)據(jù)庫主從復(fù)制的記得先去實現(xiàn)數(shù)據(jù)庫的主從復(fù)制

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

       mysqldb.properties

#主數(shù)據(jù)庫數(shù)據(jù)源
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
#從數(shù)據(jù)庫數(shù)據(jù)源
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

    主、從數(shù)據(jù)庫的地址記得改成自己的,賬號和密碼也需要改成自己的;其他配置項,大家可以酌情自行設(shè)置

       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數(shù)據(jù)源 -->
  <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}" />
    <!-- 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 -->
    <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}" />
    <!-- 申請連接時執(zhí)行validationQuery檢測連接是否有效,配置為true會降低性能 -->
    <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
    <!-- 歸還連接時執(zhí)行validationQuery檢測連接是否有效,配置為true會降低性能 -->
    <property name="testOnReturn" value="${jdbc.testOnReturn}" />
  </bean>
  <!-- slave數(shù)據(jù)源 -->
  <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>
  <!-- 動態(tài)數(shù)據(jù)源,根據(jù)service接口上的注解來決定取哪個數(shù)據(jù)源 -->
  <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>
  <!-- 事務(wù)管理器 -->
  <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"/>
  <!-- 為業(yè)務(wù)邏輯層的方法解析@DataSource注解 為當(dāng)前線程的HandleDataSource注入數(shù)據(jù)源 -->  
  <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實現(xiàn)數(shù)據(jù)源的動態(tài)切換

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對象之前,在切面中指定當(dāng)前線程數(shù)據(jù)源
   */
  public void before(JoinPoint point)
  {
    Object target = point.getTarget();
    String method = point.getSignature().getName();
    Class<?>[] classz = target.getClass().getInterfaces();            // 獲取目標(biāo)類的接口, 所以@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("用戶選擇數(shù)據(jù)庫庫類型:" + data.value());
        HandleDataSource.putDataSource(data.value());            // 數(shù)據(jù)源放到當(dāng)前線程中
      }
    } catch (Exception e)
    {
      e.printStackTrace();
    }
  }
  }

DynamicDataSource.java

package com.yzb.util;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource
{
  /**
   * 獲取與數(shù)據(jù)源相關(guān)的key 此key是Map<String,DataSource> resolvedDataSources 中與數(shù)據(jù)源綁定的key值
   * 在通過determineTargetDataSource獲取目標(biāo)數(shù)據(jù)源時使用
   */
  @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>();
  /**
   * 綁定當(dāng)前線程數(shù)據(jù)源
   * 
   * @param key
   */
  public static void putDataSource(String datasource)
  {
    holder.set(datasource);
  }
  /**
   * 獲取當(dāng)前線程的數(shù)據(jù)源
   * 
   * @return
   */
  public static String getDataSource()
  {
    return holder.get();
  }
}

service接口上應(yīng)用@DataSource實現(xiàn)數(shù)據(jù)源的指定

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")      // 指定使用從數(shù)據(jù)源
  Person getPerson(int personId);
  boolean updatePerson(Person person);
}

注意點

  測試的時候,怎么樣知道讀取的是從數(shù)據(jù)庫了? 我們可以修改從數(shù)據(jù)庫中查詢到的那條記錄的某個字段的值,以區(qū)分主、從數(shù)據(jù)庫;

       事務(wù)需要注意,盡量保證在一個數(shù)據(jù)源上進行事務(wù);

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

  項目完整工程github地址:https://github.com/youzhibing/maven-ssm-web,工程中實現(xiàn)了redis緩存,不去訪問:http://localhost:8080/maven-ssm-web/personController/showPerson是沒有問題的,當(dāng)然你可以redis服務(wù)搭建起來并集成進來;

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

上述就是小編為大家分享的在spring中使用mybatis實現(xiàn)對mysql數(shù)據(jù)庫進行讀寫分離了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI