当前位置: 移动技术网 > IT编程>开发语言>Java > 使用Spring AOP实现MySQL数据库读写分离案例分析(附demo)

使用Spring AOP实现MySQL数据库读写分离案例分析(附demo)

2019年07月22日  | 移动技术网IT编程  | 我要评论

 一、前言

分布式环境下数据库的读写分离策略是解决数据库读写性能瓶颈的一个关键解决方案,更是最大限度了提高了应用中读取 (read)数据的速度和并发量。

在进行数据库读写分离的时候,我们首先要进行数据库的主从配置,最简单的是一台master和一台slave(大型网站系统的话,当然会很复杂,这里只是分析了最简单的情况)。通过主从配置主从数据库保持了相同的数据,我们在进行读操作的时候访问从数据库slave,在进行写操作的时候访问主数据库master。这样的话就减轻了一台服务器的压力。

在进行读写分离案例分析的时候。首先,配置数据库的主从复制,mysql5.6 数据库主从(master/slave)同步安装与配置详解

当然,只是简单的为了看一下如何用代码的方式实现数据库的读写分离,完全不必要去配置主从数据库,只需要两台安装了 相同数据库的机器就可以了。

二、实现读写分离的两种方法

具体到开发中,实现读写分离常用的有两种方式:

1、第一种方式是我们最常用的方式,就是定义2个数据库连接,一个是masterdatasource,另一个是slavedatasource。更新数据时我们读取masterdatasource,查询数据时我们读取slavedatasource。这种方式很简单,我就不赘述了。

2、第二种方式动态数据源切换,就是在程序运行时,把数据源动态织入到程序中,从而选择读取主库还是从库。主要使用的技术是:annotation,spring aop ,反射。

下面会详细的介绍实现方式。

三、aop实现主从数据库的读写分离案例

1、项目代码地址

目前该demo的项目地址:

2、项目结构

上图中,除了标记的代码,其他的主要是配置代码和业务代码。

3、具体分析

该项目是ssm框架的一个demo,spring、spring mvc和mybatis,具体的配置文件不在过多介绍。

(1)usercontoller模拟读写数据

/**
 * created by xuliugen on 2016/5/4.
 */
@controller
@requestmapping(value = "/user", produces = {"application/json;charset=utf-8"})
public class usercontroller {

 @inject
 private iuserservice userservice;

 //http://localhost:8080/user/select.do
 @responsebody
 @requestmapping(value = "/select.do", method = requestmethod.get)
 public string select() {
  user user = userservice.selectuserbyid(123);
  return user.tostring();
 }

 //http://localhost:8080/user/add.do
 @responsebody
 @requestmapping(value = "/add.do", method = requestmethod.get)
 public string add() {
  boolean isok = userservice.adduser(new user("333", "444"));
  return isok == true ? "shibai" : "chenggong";
 }
}

模拟读写数据,调用iuserservice 。

(2)spring-db.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:aop="http://www.springframework.org/schema/aop"
  xsi:schemalocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

 <bean id="statfilter" class="com.alibaba.druid.filter.stat.statfilter" lazy-init="true">
  <property name="logslowsql" value="true"/>
  <property name="mergesql" value="true"/>
 </bean>

 <!-- 数据库连接 -->
 <bean id="readdatasource" class="com.alibaba.druid.pool.druiddatasource"
   destroy-method="close" init-method="init" lazy-init="true">
  <property name="driverclassname" value="${driver}"/>
  <property name="url" value="${url1}"/>
  <property name="username" value="root"/>
  <property name="password" value="${password}"/>
   <!-- 省略部分内容 -->
 </bean>

 <bean id="writedatasource" class="com.alibaba.druid.pool.druiddatasource"
   destroy-method="close" init-method="init" lazy-init="true">
  <property name="driverclassname" value="${driver}"/>
  <property name="url" value="${url}"/>
  <property name="username" value="root"/>
  <property name="password" value="${password}"/>
  <!-- 省略部分内容 -->
 </bean>

 <!-- 配置动态分配的读写 数据源 -->
 <bean id="datasource" class="com.xuliugen.choosedb.demo.aspect.choosedatasource" lazy-init="true">
  <property name="targetdatasources">
   <map key-type="java.lang.string" value-type="javax.sql.datasource">
    <!-- write -->
    <entry key="write" value-ref="writedatasource"/>
    <!-- read -->
    <entry key="read" value-ref="readdatasource"/>
   </map>
  </property>
  <property name="defaulttargetdatasource" ref="writedatasource"/>
  <property name="methodtype">
   <map key-type="java.lang.string">
    <!-- read -->
    <entry key="read" value=",get,select,count,list,query"/>
    <!-- write -->
    <entry key="write" value=",add,create,update,delete,remove,"/>
   </map>
  </property>
 </bean>

</beans>

上述配置中,配置了readdatasource和writedatasource两个数据源,但是交给sqlsessionfactorybean进行管理的只有datasource,其中使用到了:com.xuliugen.choosedb.demo.aspect.choosedatasource 这个是进行数据库选择的。

<property name="methodtype">
 <map key-type="java.lang.string">
  <!-- read -->
  <entry key="read" value=",get,select,count,list,query"/>
  <!-- write -->
  <entry key="write" value=",add,create,update,delete,remove,"/>
  </map>
</property>

配置了数据库具体的那些是读哪些是写的前缀关键字。choosedatasource的具体代码如下:

(3)choosedatasource

/**
 * 获取数据源,用于动态切换数据源
 */
public class choosedatasource extends abstractroutingdatasource {

 public static map<string, list<string>> method_type_map = new hashmap<string, list<string>>();

 /**
  * 实现父类中的抽象方法,获取数据源名称
  * @return
  */
 protected object determinecurrentlookupkey() {
  return datasourcehandler.getdatasource();
 }

 // 设置方法名前缀对应的数据源
 public void setmethodtype(map<string, string> map) {
  for (string key : map.keyset()) {
   list<string> v = new arraylist<string>();
   string[] types = map.get(key).split(",");
   for (string type : types) {
    if (stringutils.isnotblank(type)) {
     v.add(type);
    }
   }
   method_type_map.put(key, v);
  }
 }
}

(4)datasourceaspect进行具体方法的aop拦截

/**
 * 切换数据源(不同方法调用不同数据源)
 */
@aspect
@component
@enableaspectjautoproxy(proxytargetclass = true)
public class datasourceaspect {

 protected logger logger = loggerfactory.getlogger(this.getclass());

 @pointcut("execution(* com.xuliugen.choosedb.demo.mybatis.dao.*.*(..))")
 public void aspect() {
 }

 /**
  * 配置前置通知,使用在方法aspect()上注册的切入点
  */
 @before("aspect()")
 public void before(joinpoint point) {
  string classname = point.gettarget().getclass().getname();
  string method = point.getsignature().getname();
  logger.info(classname + "." + method + "(" + stringutils.join(point.getargs(), ",") + ")");
  try {
   for (string key : choosedatasource.method_type_map.keyset()) {
    for (string type : choosedatasource.method_type_map.get(key)) {
     if (method.startswith(type)) {
      datasourcehandler.putdatasource(key);
     }
    }
   }
  } catch (exception e) {
   e.printstacktrace();
  }
 }
}

(5)datasourcehandler,数据源的handler类

package com.xuliugen.choosedb.demo.aspect;

/**
 * 数据源的handler类
 */
public class datasourcehandler {

 // 数据源名称线程池
 public static final threadlocal<string> holder = new threadlocal<string>();

 /**
  * 在项目启动的时候将配置的读、写数据源加到holder中
  */
 public static void putdatasource(string datasource) {
  holder.set(datasource);
 }

 /**
  * 从holer中获取数据源字符串
  */
 public static string getdatasource() {
  return holder.get();
 }
}

主要代码,如上所述。

本文代码:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网