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

應(yīng)用服務(wù)器在寫數(shù)據(jù)的時候,訪問主數(shù)據(jù)庫,主數(shù)據(jù)庫通過主從復(fù)制機(jī)制將數(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}" />
<!-- 配置間隔多久才進(jìn)行一次檢測,檢測需要關(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
* 編譯器將把注釋記錄在類文件中,在運(yùn)行時 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);
}
注意點(diǎn)
測試的時候,怎么樣知道讀取的是從數(shù)據(jù)庫了? 我們可以修改從數(shù)據(jù)庫中查詢到的那條記錄的某個字段的值,以區(qū)分主、從數(shù)據(jù)庫;
事務(wù)需要注意,盡量保證在一個數(shù)據(jù)源上進(jìn)行事務(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ù)搭建起來并集成進(jìn)來;
測試url:http://localhost:8080/maven-ssm-web/personController/person?personId=1
總結(jié)
以上所述是小編給大家介紹的spring集成mybatis實現(xiàn)mysql數(shù)據(jù)庫讀寫分離,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Spring+Mybatis 實現(xiàn)aop數(shù)據(jù)庫讀寫分離與多數(shù)據(jù)庫源配置操作
- springboot配置內(nèi)存數(shù)據(jù)庫H2教程詳解
- 詳解spring整合shiro權(quán)限管理與數(shù)據(jù)庫設(shè)計
- Spring MVC配置雙數(shù)據(jù)源實現(xiàn)一個java項目同時連接兩個數(shù)據(jù)庫的方法
- SpringMVC4+MyBatis+SQL Server2014實現(xiàn)數(shù)據(jù)庫讀寫分離
- Spring Boot集成MyBatis訪問數(shù)據(jù)庫的方法
- Spring jdbc中數(shù)據(jù)庫操作對象化模型的實例詳解
相關(guān)文章
關(guān)于@OnetoMany關(guān)系映射的排序問題,使用注解@OrderBy
這篇文章主要介紹了關(guān)于@OnetoMany關(guān)系映射的排序問題,使用注解@OrderBy,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
基于SpringBoot?使用?Flink?收發(fā)Kafka消息的示例詳解
這篇文章主要介紹了基于SpringBoot?使用?Flink?收發(fā)Kafka消息,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01
使用Feign遠(yuǎn)程調(diào)用時,序列化對象失敗的解決
這篇文章主要介紹了使用Feign遠(yuǎn)程調(diào)用時,序列化對象失敗的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
SpringBoot如何動態(tài)改變?nèi)罩炯墑e
這篇文章主要介紹了SpringBoot如何動態(tài)改變?nèi)罩炯墑e,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-12-12

