spring多数据源配置,实现读写分离

前提:已成功搭建mysql主从集群。
mysql主从复制环境搭建
原理:首先使用spring配置动态数据源,然后使用切面拦截service方法,判断执行的是写操作还是读操作,以此来动态的修改此次请求所使用的数据源。

源码:https://github.com/li5454yong/springdatesource.git

spring配置文件:


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
    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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd 
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <description>Spring公共配置description>

    <context:component-scan base-package="com.lxg.*" />

    
    <bean id="dataSourceMaster" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.master.url}" />
        <property name="username" value="${jdbc.master.username}" />
        <property name="password" value="${jdbc.master.password}" />
    bean>

    
    <bean id="dataSourceSlaver" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.slaver.url}" />
        <property name="username" value="${jdbc.slaver.username}" />
        <property name="password" value="${jdbc.slaver.password}" />
    bean>

    <bean id="dataSource" class="com.lxg.springdatesource.DynamicDataSource">
        
        <property name="targetDataSources">
            <map>
                <entry value-ref="dataSourceMaster" key="Master">entry>
                <entry value-ref="dataSourceSlaver" key="Slaver">entry>
            map>
        property>
        <property name="defaultTargetDataSource" ref="dataSourceMaster" />
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations" value="classpath*:/mybatis/*Mapper.xml" />
        
        <property name="configLocation" value="classpath:/mybatis/config.xml" />
    bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
        
        <constructor-arg index="1" value="BATCH" />
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="com.lxg.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    bean>



    
    <tx:annotation-driven transaction-manager="transactionManager" />

    
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>

    
    <tx:advice id="txAdvice" transaction-manager="transactionManager"/>

    
    <bean class="com.lxg.springdatesource.DataSourceAspect" id="dataSourceAspect" />

    <aop:config>
        
        <aop:pointcut id="myPointcut" expression="execution(* com.lxg.service.impl.*.*(..))" />
        
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />

        
        <aop:aspect ref="dataSourceAspect" order="-9999">
            <aop:before method="before" pointcut-ref="myPointcut" />
        aop:aspect>

    aop:config>


    
    <beans>
        <context:property-placeholder
            ignore-unresolvable="true" file-encoding="utf-8" location="classpath:jdbc.properties" />
    beans>
beans>

数据库连接信息:

jdbc.driver=com.mysql.jdbc.Driver

#主数据库
jdbc.master.url=jdbc:mysql://localhost:3306/slave_lxg
jdbc.master.username=root
jdbc.master.password=root

#从数据库
jdbc.slaver.url=jdbc:mysql://192.168.0.12:3306/slave_lxg
jdbc.slaver.username=root
jdbc.slaver.password=root

aop切面:
DataSourceAspect.java

package com.lxg.springdatesource;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;

/**
 * 定义数据源的AOP切面,通过该Service的方法名判断是应该走读库还是写库
 * 
 */
public class DataSourceAspect {

    /**
     * 在进入Service方法之前执行
     * 
     * @param point 切面对象
     */
    public void before(JoinPoint point) {
        // 获取到当前执行的方法名
        String methodName = point.getSignature().getName();
        if (isSlave(methodName)) {
            // 标记为从库
            DBContextHolder.setDBType(DBContextHolder.DATA_SOURCE_SLAVER);
        } else {
            // 标记为主库
            DBContextHolder.setDBType(DBContextHolder.DATA_SOURCE_MASTER);
        }
    }

    /**
     * 判断是否为读库
     * 
     * @param methodName
     * @return
     */
    private Boolean isSlave(String methodName) {
        // 方法名以query、find、get开头的方法名走从库
        return StringUtils.startsWithAny(methodName, "query", "find", "get");
    }

}

DBContextHolder.java

package com.lxg.springdatesource;

public class DBContextHolder{  
    public static final String DATA_SOURCE_MASTER = "Master";  
    public static final String DATA_SOURCE_SLAVER = "Slaver";  

    private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();  

    public static void setDBType(String dbType) {  
        THREAD_LOCAL.set(dbType);  
    }  

    public static String getDBType() {  
        return THREAD_LOCAL.get();  
    }  

    public static void clearDBType() {  
        THREAD_LOCAL.remove();  
    }  
}  

DynamicDataSource.java

package com.lxg.springdatesource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

 public class DynamicDataSource extends AbstractRoutingDataSource{  

    @Override  
    protected Object determineCurrentLookupKey() {  
        return DBContextHolder.getDBType();  
    }  
}

你可能感兴趣的:(Java,MySQL,读写分离)