一,为什么要进行读写分离呢?
因为数据库的“写操作”操作是比较耗时的(写上万条条数据到Mysql的可能要1分钟分钟)。但是数据库的“读操作”却比“写操作”耗时要少的多(从Mysql的读几万条数据条数据可能只要十秒钟),而我们在开发过程中大多数也是查询操作比较多。所以读写分离解决的是,数据库的“写操作”影响了查询的效率问题。
二,那么怎么来进行读写分离呢?
首先,基于上一篇主从复制
那么我们现在开始基于消费满+ AOP来实现读写分离
1:配置多数据源
jdbc.properties文件如下:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url_master=jdbc:mysql://localhost:3306/longlong_bike?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.url_slaver1=jdbc:mysql://localhost:3306/longlong_bike?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.url_slaver2=jdbc:mysql://localhost:3306/longlong_bike?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=admin
2:的applicationContext文件如下:
<?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-4.0.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-4.0.xsd">
<!--打开注解-->
<context:annotation-config/>
<!--打开包扫描-->
<context:component-scan base-package="com.coder520"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--主数据库-->
<bean id="dataSource_master" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url_master}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置从数据库-->
<bean id="dataSource_slaver1" class="com.alibaba.druid.pool.DruidDataSource">