本文通过实例代码给大家介绍了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关键字控制好织入顺序;
总结
以上就是关于spring集成mybatis如何实现mysql数据库读写分离的实例分析的详细内容。