spring的配置如下
 <!-- 主数据源-->  
    <bean id="masterDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://127.0.0.1/test1?useUnicode=true&characterEncoding=utf8" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
    </bean>
          
    <!-- 从数据源-->  
    <bean id="slaveDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://127.0.0.1/test2?useUnicode=true&characterEncoding=utf8" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
    </bean>  
	
	 <bean id="dataSource" class="c.p.aop.DynamicDataSource">  
        <property name="targetDataSources">  
            <map key-type="java.lang.String">  
                <entry key="slave" value-ref="slaveDataSource" />
                <entry key="master" value-ref="masterDataSource" />  
            </map>  
        </property>  
        <property name="defaultTargetDataSource" ref="masterDataSource" />  
    </bean>  
	
	
	
	<!-- 配置 jdbcTemplate,可通过jdbcTemplate直接操作数据库-->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 配置公共类对象 -->
	<bean id="baseDao" class="cq.base.dao.impl.SSH2BaseDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- 配置公共类对象
	<bean id="pageDao" class="cq.base.dao.impl.PageDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean> -->
	
	<!-- 配置sessionFactory ,注解模式的配置-->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="c.p.entity" />
		<property name="annotatedClasses">
			<list>
				<value>cq.base.entity.LogBean</value>
			</list>
		</property>
		
		<property name="hibernateProperties">
			<props>
				<!-- <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> -->
				<!-- <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>-->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.cache.use_second_level_cache">true</prop>
				<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
				<prop key="hibernate.cache.use_query_cache">true</prop>
			</props>
		</property>
	</bean> 
	
	<!-- 切换数据源 -->  
    <bean id="dataSourceAdvice" class="c.p.aop.DataSourceAdvice"></bean>
      
    <aop:config>  
        <aop:pointcut id="businessService" expression="execution(* *..*Service.*(..))" />
        <aop:advisor  pointcut-ref="businessService" advice-ref="dataSourceAdvice" />
    </aop:config>  
这里需要三个类配合
DynamicDataSource <pre name="code" class="html">DataSourceAdvice
<pre name="code" class="html">DataSourceSwitcher
c.p.aop.DynamicDataSource.java如下:
public  class DynamicDataSource extends AbstractRoutingDataSource {  
  
    @Override  
    protected Object determineCurrentLookupKey() {  
        return DataSourceSwitcher.getDataSource();  
    }
	public Logger getParentLogger() {
		// TODO Auto-generated method stub
		return null;
	}
	public <T> T unwrap(Class<T> iface,String m) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}
	public boolean isWrapperFor(Class<?> iface,String m) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}  
  
}  c.p.aop.DataSourceAdvice.java,配置如下
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("add")  
            || method.getName().startsWith("update")  
            || method.getName().startsWith("delete")){  
            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");  
    }  
  
}
<pre name="code" class="html">DataSourceSwitcher.java代码如下
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();  
    }  
}
我们可以按照以下步骤实现
1.配置主数据库的my.ini文件,在最后面加入
#---------------------------------------------
server-id=242
log-bin=mysql-bin
relay-log=relay-bin
relay-log-index=relay-bin-index
replicate-do-db=要同步的数据库
#---------------------------------------------
重启mysql服务。
2.从数据库也配置对应的my.ini文件
#---------------------------------------------
server-id=243
log-bin=mysql-bin
relay-log=relay-bin
relay-log-index=relay-bin-index
replicate-do-db=要同步的数据库
#---------------------------------------------
重启mysql服务。
从数据库敲打以下命令
服务242上用MySQL命令行工具执行如下语句:
mysql> stop slave;
mysql> change master to master_host=‘主数据库ip‘,master_user=‘root‘,master_password=‘abcd‘;
mysql> start slave;
mysql> show slave status\G;
这样就可以实现同步的问题了。
spring hibernate配置切换数据源,实现读写分离
原文:http://blog.csdn.net/yeyincai/article/details/39472289