深入理解spring多数据源配置
程序员文章站
2024-03-08 14:15:28
项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring...
项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和hibernate的框架的项目中,我们在spring配置中往往是配置一个datasource来连接数据库,然后绑定给sessionfactory,在dao层代码中再指定sessionfactory来进行数据库操作。
正如上图所示,每一块都是指定绑死的,如果是多个数据源,也只能是下图中那种方式。
可看出在dao层代码中写死了两个sessionfactory,这样日后如果再多一个数据源,还要改代码添加一个sessionfactory,显然这并不符合开闭原则。
那么正确的做法应该是
代码如下:
1. applicationcontext.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:cache="http://www.springframework.org/schema/cache" 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:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <context:annotation-config /> <context:component-scan base-package="com"></context:component-scan> <bean class="org.springframework.beans.factory.config.propertyplaceholderconfigurer"> <property name="locations"> <list> <value>classpath:com/resource/config.properties</value> </list> </property> </bean> <bean id="datasourceone" class="com.mchange.v2.c3p0.combopooleddatasource" destroy-method="close"> <property name="driverclass" value="${dbone.jdbc.driverclass}" /> <property name="jdbcurl" value="${dbone.jdbc.url}" /> <property name="user" value="${dbone.jdbc.user}" /> <property name="password" value="${dbone.jdbc.password}" /> <property name="initialpoolsize" value="${dbone.jdbc.initialpoolsize}" /> <property name="minpoolsize" value="${dbone.jdbc.minpoolsize}" /> <property name="maxpoolsize" value="${dbone.jdbc.maxpoolsize}" /> </bean> <bean id="datasourcetwo" class="com.mchange.v2.c3p0.combopooleddatasource" destroy-method="close"> <property name="driverclass" value="${dbtwo.jdbc.driverclass}" /> <property name="jdbcurl" value="${dbtwo.jdbc.url}" /> <property name="user" value="${dbtwo.jdbc.user}" /> <property name="password" value="${dbtwo.jdbc.password}" /> <property name="initialpoolsize" value="${dbtwo.jdbc.initialpoolsize}" /> <property name="minpoolsize" value="${dbtwo.jdbc.minpoolsize}" /> <property name="maxpoolsize" value="${dbtwo.jdbc.maxpoolsize}" /> </bean> <bean id="dynamicdatasource" class="com.core.dynamicdatasource"> <property name="targetdatasources"> <map key-type="java.lang.string"> <entry value-ref="datasourceone" key="datasourceone"></entry> <entry value-ref="datasourcetwo" key="datasourcetwo"></entry> </map> </property> <property name="defaulttargetdatasource" ref="datasourceone"> </property> </bean> <bean id="sessionfactory" class="org.springframework.orm.hibernate4.localsessionfactorybean"> <property name="datasource" ref="dynamicdatasource" /> <property name="hibernateproperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.mysqldialect</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.springsessioncontext</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hbm2ddl.auto">create</prop> </props> </property> <property name="packagestoscan"> <list> <value>com.po</value> </list> </property> </bean> <bean id="transactionmanager" class="org.springframework.orm.hibernate4.hibernatetransactionmanager"> <property name="sessionfactory" ref="sessionfactory" /> </bean> <aop:config> <aop:pointcut id="transactionpointcut" expression="execution(* com.dao..*.*(..))" /> <aop:advisor advice-ref="txadvice" pointcut-ref="transactionpointcut" /> </aop:config> <tx:advice id="txadvice" transaction-manager="transactionmanager"> <tx:attributes> <tx:method name="add*" propagation="required" /> <tx:method name="save*" propagation="required" /> <tx:method name="update*" propagation="required" /> <tx:method name="delete*" propagation="required" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:aspect id="datasourceaspect" ref="datasourceinterceptor"> <aop:pointcut id="daoone" expression="execution(* com.dao.one.*.*(..))" /> <aop:pointcut id="daotwo" expression="execution(* com.dao.two.*.*(..))" /> <aop:before pointcut-ref="daoone" method="setdatasourceone" /> <aop:before pointcut-ref="daotwo" method="setdatasourcetwo" /> </aop:aspect> </aop:config> </beans>
2. dynamicdatasource.class
package com.core; import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource; public class dynamicdatasource extends abstractroutingdatasource{ @override protected object determinecurrentlookupkey() { return databasecontextholder.getcustomertype(); } }
3. databasecontextholder.class
package com.core; public class databasecontextholder { private static final threadlocal<string> contextholder = new threadlocal<string>(); public static void setcustomertype(string customertype) { contextholder.set(customertype); } public static string getcustomertype() { return contextholder.get(); } public static void clearcustomertype() { contextholder.remove(); } }
4. datasourceinterceptor.class
package com.core; import org.aspectj.lang.joinpoint; import org.springframework.stereotype.component; @component public class datasourceinterceptor { public void setdatasourceone(joinpoint jp) { databasecontextholder.setcustomertype("datasourceone"); } public void setdatasourcetwo(joinpoint jp) { databasecontextholder.setcustomertype("datasourcetwo"); } }
5. po实体类
package com.po; import javax.persistence.column; import javax.persistence.entity; import javax.persistence.id; import javax.persistence.table; @entity @table(name = "btsf_brand", schema = "hotel") public class brand { private string id; private string names; private string url; @id @column(name = "id", unique = true, nullable = false, length = 10) public string getid() { return this.id; } public void setid(string id) { this.id = id; } @column(name = "names", nullable = false, length = 50) public string getnames() { return this.names; } public void setnames(string names) { this.names = names; } @column(name = "url", length = 200) public string geturl() { return this.url; } public void seturl(string url) { this.url = url; } }
package com.po; import javax.persistence.column; import javax.persistence.entity; import javax.persistence.id; import javax.persistence.table; @entity @table(name = "city", schema = "car") public class city { private integer id; private string name; @id @column(name = "id", unique = true, nullable = false) public integer getid() { return id; } public void setid(integer id) { this.id = id; } @column(name = "names", nullable = false, length = 50) public string getname() { return name; } public void setname(string name) { this.name = name; } }
6. branddaoimpl.class
package com.dao.one; import java.util.list; import javax.annotation.resource; import org.hibernate.query; import org.hibernate.sessionfactory; import org.springframework.stereotype.repository; import com.po.brand; @repository public class branddaoimpl implements ibranddao { @resource protected sessionfactory sessionfactory; @suppresswarnings("unchecked") @override public list<brand> findall() { string hql = "from brand"; query query = sessionfactory.getcurrentsession().createquery(hql); return query.list(); } }
7. citydaoimpl.class
package com.dao.two; import java.util.list; import javax.annotation.resource; import org.hibernate.query; import org.hibernate.sessionfactory; import org.springframework.stereotype.repository; import com.po.city; @repository public class citydaoimpl implements icitydao { @resource private sessionfactory sessionfactory; @suppresswarnings("unchecked") @override public list<city> find() { string hql = "from city"; query query = sessionfactory.getcurrentsession().createquery(hql); return query.list(); } }
8. daotest.class
package com.test; import java.util.list; import javax.annotation.resource; import org.junit.test; import org.junit.runner.runwith; import org.springframework.test.context.contextconfiguration; import org.springframework.test.context.junit4.springjunit4classrunner; import org.springframework.test.context.transaction.transactionconfiguration; import com.dao.one.ibranddao; import com.dao.two.icitydao; import com.po.brand; import com.po.city; @runwith(springjunit4classrunner.class) @contextconfiguration(locations = "classpath:com/resource/applicationcontext.xml") @transactionconfiguration(transactionmanager = "transactionmanager", defaultrollback = false) public class daotest { @resource private ibranddao branddao; @resource private icitydao citydao; @test public void testlist() { list<brand> brands = branddao.findall(); system.out.println(brands.size()); list<city> cities = citydao.find(); system.out.println(cities.size()); } }
利用aop,达到动态更改数据源的目的。当需要增加数据源的时候,我们只需要在applicationcontext配置文件中添加aop配置,新建个datasourceinterceptor即可。而不需要更改任何代码。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。