本文只要介绍的是Hibernate+mysql在项目中的读写分离配置,具体配置文件如下:
1、配置jdbc.properties
Java代码
master.jdbc.driverClassName=com.mysql.jdbc.Driver
master.jdbc.url=192.168.88.1
master.jdbc.username=root
master.jdbc.password=root
slave.jdbc.driverClassName=com.mysql.jdbc.Driver
slave.jdbc.url=192.168.88.2
slave.jdbc.username=root
slave.jdbc.password=root
主从数据库用户名、密码可自定义
2、编写AOP切面类DataSourceAdvice.java
package com.xxxx.aop.datasource;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
import com.xxxx.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
package com.xxxx.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
package com.xxxx.datasource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceSwitcher.getDataSource();
}
}
以上为数据源选择切换的代码实现。
3、配置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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context" 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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<context:annotation-config />
<!-- 自动加载SERVICE DAO ACTION -->
<context:component-scan base-package="com.xxxx.dao.*, com.xxxx.service.*, com.xxxx.controller.*" />
<!-- 加载properties配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- c3p0配置
<bean id="parentDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
</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>
-->
<!-- 数据源配置,使用druid数据库连接池 -->
<bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${master.jdbc.url}" />
<property name="username" value="${master.jdbc.username}" />
<property name="password" value="${master.jdbc.password}" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="3000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
<property name="filters" value="stat" />
<!--配置密码是否进行加密处理 java -cp druid-0.2.23.jar com.alibaba.druid.filter.config.ConfigTools your_pass -->
<property name="connectionProperties" value="config.decrypt=true" />
</bean>
<bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${slave.jdbc.url}" />
<property name="username" value="${slave.jdbc.username}" />
<property name="password" value="${slave.jdbc.password}" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="3000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
<property name="filters" value="stat" />
<!--配置密码是否进行加密处理 java -cp druid-0.2.23.jar com.alibaba.druid.filter.config.ConfigTools your_pass -->
<property name="connectionProperties" value="config.decrypt=true" />
</bean>
本示例提供了c3p0和druid两种数据库连接方式,仅供参考
<bean id="dataSource" class="com.xxxx.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="com.xxxx.entity" />
<property name="hibernateProperties">
<props>
<prop>//***这里可以配置hibernate的一些参数</prop>
</props>
</property>
</bean>
<!-- 切换数据源 -->
<bean id="dataSourceAdvice" class="com.xxxx.aop.DataSourceAdvice" />
<aop:config>
<aop:advisor
pointcut="execution(* com.xxxx.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(* com.xxxx.service..*Service.*(..))"
advice-ref="txAdvice" />
<aop:advisor
pointcut="execution(* com.xxxx.service..*ServiceImpl.*(..))"
advice-ref="txAdvice" />
</aop:config>
</beans>
在 applicationContenxt.xml中 需要注意的是
<!-- 切换数据源 -->
<bean id="dataSourceAdvice" class="com.xxxx.aop.DataSourceAdvice" />
<aop:config>
<aop:advisor
pointcut="execution(* com.xxxx.service..*Service.*(..))"
advice-ref="dataSourceAdvice" />
</aop:config>
这个配置一定要配置在事务AOP之上