Spring+Hibernate双数据源测试Mysql集群读写分离

这一篇文章主要是对上一篇文章:Windows 平台下的Mysql集群主从复制

进行测试!环境就是SH框架、当然这只是一个简单的测试!

准备环境就是Spring框架跟Hibernate框架的整合!

然后在Spring配置文件中配置两个数据源、这里我采用的是从c3po数据源配置:

注:配置文件中的url里面要加"&"符号的话得这样写"&"

<?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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<!-- 读  -->
	<!--<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  -->
		<!-- 定义数据源Bean,使用C3P0数据源实现 -->
		 <bean id="dataSourceR" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		  <!-- 指定连接数据库的驱动 -->
		  <property name="driverClass" value="com.mysql.jdbc.Driver"/>
		  <!-- 指定连接数据库的URL -->
		  <property name="jdbcUrl" value="jdbc:mysql:loadbalance://10.11.0.75:3306,172.16.0.202:3306/DB_TEST7?roundRobinLoadBalance=true&characterEncoding=UTF-8"/>
		  <!-- 指定连接数据库的用户名 -->
		  <property name="user" value="TESTUSER"/>
		  <!-- 指定连接数据库的密码 -->
		  <property name="password" value="TESTPWD"/>
		  <!-- 指定连接数据库连接池的最大连接数 -->
		  <property name="maxPoolSize" value="20"/>
		  <!-- 指定连接数据库连接池的最小连接数 --> 
		  <property name="minPoolSize" value="1"/>
		  <!-- 指定连接数据库连接池的初始化连接数 -->
		  <property name="initialPoolSize" value="1"/>
		  <!-- 指定连接数据库连接池的连接的最大空闲时间 -->
		  <property name="maxIdleTime" value="20"/>
		 </bean>
		<!--定义了Hibernate的SessionFactory -->
			    <bean id="sessionFactoryR" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
			        <property name="dataSource" ref="dataSourceR"/>
			        <property name="mappingResources">
			            <list>
			            </list>
			        </property>
			        <property name="hibernateProperties">
			            <props>
			                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
			                <prop key="show_sql">true</prop>
			                <prop key="hibernate.hbm2ddl.auto">update</prop>
			                <prop key="hibernate.jdbc.batch_size">20</prop> 
			            </props>
			        </property>
			    </bean>
			    <bean id="transactionManagerR" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
			        <property name="sessionFactory" ref="sessionFactoryR"/>
			    </bean>
			    <bean id="transactionInterceptorR" class="org.springframework.transaction.interceptor.TransactionInterceptor">
			     <!--  事务拦截器bean需要依赖注入一个事务管理器 -->
			        <property name="transactionManager" ref="transactionManagerR"/>
			     <property name="transactionAttributes">
			      <!--  下面定义事务传播属性-->
			      <props>
			       <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
			       <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
			      </props>
			     </property>
			 	</bean>
			<bean id="daoR" class="com.boxun.test.dao.impl.daoR" >
				<property name="sessionFactory">
					<ref bean="sessionFactoryR" />
				</property>  
			</bean>
	
	<!-- 写   -->
	<bean id="dataSourceW" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		  <!-- 指定连接数据库的驱动 -->
		  <property name="driverClass" value="com.mysql.jdbc.Driver"/>
		  <!-- 指定连接数据库的URL -->
		  <property name="jdbcUrl" value="jdbc:mysql:loadbalance://10.11.2.126:3306/DB_TEST7?roundRobinLoadBalance=true&characterEncoding=UTF-8"/>
		  <!-- 指定连接数据库的用户名 -->
		  <property name="user" value="TESTUSER"/>
		  <!-- 指定连接数据库的密码 -->
		  <property name="password" value="TESTPWD"/>
		  <!-- 指定连接数据库连接池的最大连接数 -->
		  <property name="maxPoolSize" value="20"/>
		  <!-- 指定连接数据库连接池的最小连接数 -->
		  <property name="minPoolSize" value="1"/>
		  <!-- 指定连接数据库连接池的初始化连接数 -->
		  <property name="initialPoolSize" value="1"/>
		  <!-- 指定连接数据库连接池的连接的最大空闲时间 -->
		  <property name="maxIdleTime" value="20"/>
		 </bean>
		<!--定义了Hibernate的SessionFactory -->
			    <bean id="sessionFactoryW" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
			        <property name="dataSource" ref="dataSourceW"/>
			        <property name="mappingResources">
			            <list>
			            </list>
			        </property>
			        <property name="hibernateProperties">
			            <props>
			                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
			                <prop key="show_sql">true</prop>
			                <prop key="hibernate.hbm2ddl.auto">update</prop>
			                <prop key="hibernate.jdbc.batch_size">20</prop> 
			            </props>
			        </property>
			    </bean>
			    <bean id="transactionManagerW" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
			        <property name="sessionFactory" ref="sessionFactoryW"/>
			    </bean>
			    <bean id="transactionInterceptorW" class="org.springframework.transaction.interceptor.TransactionInterceptor">
			     <!--  事务拦截器bean需要依赖注入一个事务管理器 -->
			        <property name="transactionManager" ref="transactionManagerW"/>
			     <property name="transactionAttributes">
			      <!--  下面定义事务传播属性-->
			      <props>
			       <prop key="*">PROPAGATION_REQUIRED</prop>
			      </props>  
			     </property>
			 	</bean>
			 	
			 	<bean id="daoW" class="com.boxun.test.dao.impl.daoW" >
				<property name="sessionFactory">
					<ref bean="sessionFactoryW" />
				</property>  
			</bean>
</beans>


读的Dao:

public class daoR extends HibernateDaoSupport implements IdaoR{
	private Query query = null;
	public List find(String sql){
		query = super.getSession().createSQLQuery(sql);
		return query.list();
	}
}   

写的Dao:

public class daoW extends HibernateDaoSupport implements IdaoW{
	private Query query = null;
	public void save(String sql){
		Transaction t = super.getSession().beginTransaction();
		query = super.getSession().createSQLQuery(sql);
		query.executeUpdate();  
		t.commit();
	}
}

测试main方法:

public class Test {
	public static void main(String[] args) {
		ApplicationContext context=new FileSystemXmlApplicationContext("/WebRoot/WEB-INF/classes/applicationContext.xml");
		IdaoR daor =(IdaoR) context.getBean("daoR");
		IdaoW daow =(IdaoW) context.getBean("daoW");
		daow.save("insert into city(sname) values('Spring双数据源')");
		List list = daor.find("select * from city where sname = 'Spring双数据源'");
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[])list.get(i);
			System.out.println(obj[0]+" --- "+obj[1]);
		}
	}
}  

输出:

log4j:WARN No appenders could be found for logger (org.springframework.context.support.FileSystemXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
5 --- Spring双数据源

测试成功!!!


你可能感兴趣的:(Spring+Hibernate双数据源测试Mysql集群读写分离)