在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

深入理解spring多数据源配置

2017-3-7 12:50| 发布者: zhangjf| 查看: 1125| 评论: 0

摘要: 项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和hibernate的框架的项目中,我们在s ...

项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和hibernate的框架的项目中,我们在spring配置中往往是配置一个dataSource来连接数据库,然后绑定给sessionFactory,在dao层代码中再指定sessionFactory来进行数据库操作。

正如上图所示,每一块都是指定绑死的,如果是多个数据源,也只能是下图中那种方式。

可看出在Dao层代码中写死了两个SessionFactory,这样日后如果再多一个数据源,还要改代码添加一个SessionFactory,显然这并不符合开闭原则。

那么正确的做法应该是

代码如下:

1. applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:cache="http://www.springframework.org/schema/cache"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
  7. xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
  8. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
  9. xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
  10. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
  11. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  12. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
  13. http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
  14. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
  15. http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
  16. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
  17. http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
  18. http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
  19. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  20. http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
  21. http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
  22. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  23. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
  24. <context:annotation-config />
  25. <context:component-scan base-package="com"></context:component-scan>
  26. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  27. <property name="locations">
  28. <list>
  29. <value>classpath:com/resource/config.properties</value>
  30. </list>
  31. </property>
  32. </bean>
  33. <bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  34. destroy-method="close">
  35. <property name="driverClass" value="${dbOne.jdbc.driverClass}" />
  36. <property name="jdbcUrl" value="${dbOne.jdbc.url}" />
  37. <property name="user" value="${dbOne.jdbc.user}" />
  38. <property name="password" value="${dbOne.jdbc.password}" />
  39. <property name="initialPoolSize" value="${dbOne.jdbc.initialPoolSize}" />
  40. <property name="minPoolSize" value="${dbOne.jdbc.minPoolSize}" />
  41. <property name="maxPoolSize" value="${dbOne.jdbc.maxPoolSize}" />
  42. </bean>
  43. <bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  44. destroy-method="close">
  45. <property name="driverClass" value="${dbTwo.jdbc.driverClass}" />
  46. <property name="jdbcUrl" value="${dbTwo.jdbc.url}" />
  47. <property name="user" value="${dbTwo.jdbc.user}" />
  48. <property name="password" value="${dbTwo.jdbc.password}" />
  49. <property name="initialPoolSize" value="${dbTwo.jdbc.initialPoolSize}" />
  50. <property name="minPoolSize" value="${dbTwo.jdbc.minPoolSize}" />
  51. <property name="maxPoolSize" value="${dbTwo.jdbc.maxPoolSize}" />
  52. </bean>
  53. <bean id="dynamicDataSource" class="com.core.DynamicDataSource">
  54. <property name="targetDataSources">
  55. <map key-type="java.lang.String">
  56. <entry value-ref="dataSourceOne" key="dataSourceOne"></entry>
  57. <entry value-ref="dataSourceTwo" key="dataSourceTwo"></entry>
  58. </map>
  59. </property>
  60. <property name="defaultTargetDataSource" ref="dataSourceOne">
  61. </property>
  62. </bean>
  63. <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  64. <property name="dataSource" ref="dynamicDataSource" />
  65. <property name="hibernateProperties">
  66. <props>
  67. <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
  68. <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
  69. <prop key="hibernate.show_sql">false</prop>
  70. <prop key="hibernate.format_sql">true</prop>
  71. <prop key="hbm2ddl.auto">create</prop>
  72. </props>
  73. </property>
  74. <property name="packagesToScan">
  75. <list>
  76. <value>com.po</value>
  77. </list>
  78. </property>
  79. </bean>
  80. <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  81. <property name="sessionFactory" ref="sessionFactory" />
  82. </bean>
  83. <aop:config>
  84. <aop:pointcut id="transactionPointCut" expression="execution(* com.dao..*.*(..))" />
  85. <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" />
  86. </aop:config>
  87. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  88. <tx:attributes>
  89. <tx:method name="add*" propagation="REQUIRED" />
  90. <tx:method name="save*" propagation="REQUIRED" />
  91. <tx:method name="update*" propagation="REQUIRED" />
  92. <tx:method name="delete*" propagation="REQUIRED" />
  93. <tx:method name="*" read-only="true" />
  94. </tx:attributes>
  95. </tx:advice>
  96. <aop:config>
  97. <aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
  98. <aop:pointcut id="daoOne" expression="execution(* com.dao.one.*.*(..))" />
  99. <aop:pointcut id="daoTwo" expression="execution(* com.dao.two.*.*(..))" />
  100. <aop:before pointcut-ref="daoOne" method="setdataSourceOne" />
  101. <aop:before pointcut-ref="daoTwo" method="setdataSourceTwo" />
  102. </aop:aspect>
  103. </aop:config>
  104. </beans>
复制代码

2. DynamicDataSource.class

  1. package com.core;
  2. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
  3. public class DynamicDataSource extends AbstractRoutingDataSource{
  4. @Override
  5. protected Object determineCurrentLookupKey() {
  6. return DatabaseContextHolder.getCustomerType();
  7. }
  8. }
复制代码

3. DatabaseContextHolder.class

  1. package com.core;
  2. public class DatabaseContextHolder {
  3. private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
  4. public static void setCustomerType(String customerType) {
  5. contextHolder.set(customerType);
  6. }
  7. public static String getCustomerType() {
  8. return contextHolder.get();
  9. }
  10. public static void clearCustomerType() {
  11. contextHolder.remove();
  12. }
  13. }
复制代码

4. DataSourceInterceptor.class

  1. package com.core;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class DataSourceInterceptor {
  6. public void setdataSourceOne(JoinPoint jp) {
  7. DatabaseContextHolder.setCustomerType("dataSourceOne");
  8. }
  9. public void setdataSourceTwo(JoinPoint jp) {
  10. DatabaseContextHolder.setCustomerType("dataSourceTwo");
  11. }
  12. }
复制代码

5. po实体类

  1. package com.po;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.Id;
  5. import javax.persistence.Table;
  6. @Entity
  7. @Table(name = "BTSF_BRAND", schema = "hotel")
  8. public class Brand {
  9. private String id;
  10. private String names;
  11. private String url;
  12. @Id
  13. @Column(name = "ID", unique = true, nullable = false, length = 10)
  14. public String getId() {
  15. return this.id;
  16. }
  17. public void setId(String id) {
  18. this.id = id;
  19. }
  20. @Column(name = "NAMES", nullable = false, length = 50)
  21. public String getNames() {
  22. return this.names;
  23. }
  24. public void setNames(String names) {
  25. this.names = names;
  26. }
  27. @Column(name = "URL", length = 200)
  28. public String getUrl() {
  29. return this.url;
  30. }
  31. public void setUrl(String url) {
  32. this.url = url;
  33. }
  34. }
复制代码
  1. package com.po;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.Id;
  5. import javax.persistence.Table;
  6. @Entity
  7. @Table(name = "CITY", schema = "car")
  8. public class City {
  9. private Integer id;
  10. private String name;
  11. @Id
  12. @Column(name = "ID", unique = true, nullable = false)
  13. public Integer getId() {
  14. return id;
  15. }
  16. public void setId(Integer id) {
  17. this.id = id;
  18. }
  19. @Column(name = "NAMES", nullable = false, length = 50)
  20. public String getName() {
  21. return name;
  22. }
  23. public void setName(String name) {
  24. this.name = name;
  25. }
  26. }
复制代码

6. BrandDaoImpl.class

  1. package com.dao.one;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.hibernate.Query;
  5. import org.hibernate.SessionFactory;
  6. import org.springframework.stereotype.Repository;
  7. import com.po.Brand;
  8. @Repository
  9. public class BrandDaoImpl implements IBrandDao {
  10. @Resource
  11. protected SessionFactory sessionFactory;
  12. @SuppressWarnings("unchecked")
  13. @Override
  14. public List<Brand> findAll() {
  15. String hql = "from Brand";
  16. Query query = sessionFactory.getCurrentSession().createQuery(hql);
  17. return query.list();
  18. }
  19. }
复制代码

7. CityDaoImpl.class

  1. package com.dao.two;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.hibernate.Query;
  5. import org.hibernate.SessionFactory;
  6. import org.springframework.stereotype.Repository;
  7. import com.po.City;
  8. @Repository
  9. public class CityDaoImpl implements ICityDao {
  10. @Resource
  11. private SessionFactory sessionFactory;
  12. @SuppressWarnings("unchecked")
  13. @Override
  14. public List<City> find() {
  15. String hql = "from City";
  16. Query query = sessionFactory.getCurrentSession().createQuery(hql);
  17. return query.list();
  18. }
  19. }
复制代码

8. DaoTest.class

  1. package com.test;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8. import org.springframework.test.context.transaction.TransactionConfiguration;
  9. import com.dao.one.IBrandDao;
  10. import com.dao.two.ICityDao;
  11. import com.po.Brand;
  12. import com.po.City;
  13. @RunWith(SpringJUnit4ClassRunner.class)
  14. @ContextConfiguration(locations = "classpath:com/resource/applicationContext.xml")
  15. @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
  16. public class DaoTest {
  17. @Resource
  18. private IBrandDao brandDao;
  19. @Resource
  20. private ICityDao cityDao;
  21. [url=home.php?mod=space&uid=5447]@test[/url]
  22. public void testList() {
  23. List<Brand> brands = brandDao.findAll();
  24. System.out.println(brands.size());
  25. List<City> cities = cityDao.find();
  26. System.out.println(cities.size());
  27. }
  28. }
复制代码

利用aop,达到动态更改数据源的目的。当需要增加数据源的时候,我们只需要在applicationContext配置文件中添加aop配置,新建个DataSourceInterceptor即可。而不需要更改任何代码。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-4 02:33

Copyright 2015-2025 djqfx

返回顶部