Spring+Hibernate框架下MySql讀寫分離,主從資料庫配置 (轉)

iteye_19594發表於2014-06-12

介紹下mysql資料庫讀寫分離在spring,hibernate框架下的配置。
1.mysql連線配置檔案jdbc.properties
master.*.*表示主資料庫連線引數,負責增,刪,改;
slave.*.*表示從資料庫連線引數,只負責讀取;

jdbc.properties
Java程式碼
master.jdbc.driverClassName=com.mysql.jdbc.Driver
master.jdbc.url=********
master.jdbc.username=********
master.jdbc.password=********

slave.jdbc.driverClassName=com.mysql.jdbc.Driver
slave.jdbc.url=********
slave.jdbc.username=********
slave.jdbc.password=********

把**改成你所需的連線引數;

2.配置AOP切面類 DataSourceAdvice.java
Java程式碼
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

import com.company.datasource.DataSourceSwitcher;

public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {
    // service方法執行之前被呼叫
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("切入點: " + target.getClass().getName() + "類中" + method.getName() + "方法");
        if(method.getName().startsWith("add")
            || method.getName().startsWith("create")
            || method.getName().startsWith("save")
            || method.getName().startsWith("edit")
            || method.getName().startsWith("update")
            || method.getName().startsWith("delete")
            || method.getName().startsWith("remove")){
            System.out.println("切換到: master");
            DataSourceSwitcher.setMaster();
        }
        else  {
            System.out.println("切換到: slave");
            DataSourceSwitcher.setSlave();
        }
    }

    // service方法執行完之後被呼叫
    public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {
    }

    // 丟擲Exception之後被呼叫
    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
        DataSourceSwitcher.setSlave();
        System.out.println("出現異常,切換到: slave");
    }

}

資料來源選擇類 DataSourceSwitcher.java
Java程式碼
package com.company.datasource;
import org.springframework.util.Assert;

public class DataSourceSwitcher {
    @SuppressWarnings("rawtypes")
    private static final ThreadLocal contextHolder = new ThreadLocal();

    @SuppressWarnings("unchecked")
    public static void setDataSource(String dataSource) {
        Assert.notNull(dataSource, "dataSource cannot be null");
        contextHolder.set(dataSource);
    }

    public static void setMaster(){
        clearDataSource();
    }
   
    public static void setSlave() {
        setDataSource("slave");
    }
   
    public static String getDataSource() {
        return (String) contextHolder.get();
    }

    public static void clearDataSource() {
        contextHolder.remove();
    }
}

DynamicDataSource.java資料來源動態切換類
Java程式碼
package com.company.datasource;

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

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceSwitcher.getDataSource();
    }

}

下面配置spring applicationContext.xml檔案
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"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config />
    <!-- 自動載入SERVICE DAO ACTION -->
    <context:component-scan base-package="cn.com.company.dao.*" />
    <context:component-scan base-package="cn.com.company.service.*" />
    <context:component-scan base-package="cn.com.company.action" />

    <!-- 載入properties配置檔案 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>

    <bean id="parentDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        //***c3p0配置
    </bean>
     <!-- 主資料來源-->
    <bean id="masterDataSource" parent="parentDataSource">
        <property name="driverClass" value="${master.jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${master.jdbc.url}" />
        <property name="user" value="${master.jdbc.username}" />
        <property name="password" value="${master.jdbc.password}" />
    </bean>
    <!-- 從資料來源-->
    <bean id="slaveDataSource" parent="parentDataSource">
        <property name="driverClass" value="${slave.jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${slave.jdbc.url}" />
        <property name="user" value="${slave.jdbc.username}" />
        <property name="password" value="${slave.jdbc.password}" />
    </bean>

    <bean id="dataSource" class="com.company.datasource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="slave" value-ref="slaveDataSource" />
            </map>
        </property>
        <property name="defaultTargetDataSource" ref="masterDataSource" />
    </bean>

    <!-- 配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="cn.com.company.entity" />
        <property name="hibernateProperties">
            <props>

                <prop>//***hibernate一些引數這裡不寫了</prop>
            </props>
        </property>
    </bean>
   
    <!-- 切換資料來源 -->
    <bean id="dataSourceAdvice" class="com.company.aop.DataSourceAdvice" />
    <aop:config>
        <aop:advisor
            pointcut="execution(* cn.com.company.service..*Service.*(..))"
            advice-ref="dataSourceAdvice" />
    </aop:config>
   
    <!-- 配置事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <!--配置事務的傳播特性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 對增、刪、改方法進行事務支援 -->
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <!-- 對查詢方法進行只讀事務 -->
            <tx:method name="loadByUsername*" propagation="SUPPORTS" read-only="true" />
            <!-- 對其它方法進行只讀事務 -->
            <tx:method name="*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!--那些類的哪些方法參與事務 -->
    <aop:config>
        <aop:advisor
            pointcut="execution(* cn.com.company.service..*Service.*(..))"
            advice-ref="txAdvice" />
        <aop:advisor
            pointcut="execution(* cn.com.company.service..*ServiceImpl.*(..))"
            advice-ref="txAdvice" />
    </aop:config>
</beans>


!注 applicationContenxt.xml中
<!-- 切換資料來源 -->
<bean id="dataSourceAdvice" class="com.company.aop.DataSourceAdvice" />
<aop:config>
<aop:advisor
pointcut="execution(* cn.com.company.service..*Service.*(..))"
advice-ref="dataSourceAdvice" />
</aop:config>
一定要配置在事務AOP之上

相關文章