MySQL多数据源 二(基于spring+aop实现读写分离)

本文探讨了数据库读写分离的原因,详细介绍了如何利用Spring和AOP实现读写分离,包括配置多数据源、动态切换数据源的类以及通过切面和注解简化代码。同时,文章提到了读写分离可能引发的数据不一致性和在修改查询同时操作时的问题,并给出了相应的处理策略。
摘要由CSDN通过智能技术生成

一,为什么要进行读写分离呢?

  因为数据库的“写操作”操作是比较耗时的(写上万条条数据到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">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值