全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

深入理解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即可。而不需要更改任何代码。

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


# spring配置多个数据源  # spring  # 多数据源  # 数据源  # 详解Spring Boot整合Mybatis实现 Druid多数据源配置  # spring+Jpa多数据源配置的方法示例  # 详解基于Spring Boot与Spring Data JPA的多数据源配置  # Spring+MyBatis多数据源配置实现示例  # springboot-mongodb的多数据源配置的方法步骤  # springboot v2.0.3版本多数据源配置方法  # Spring动态多数据源配置实例Demo  # Spring Boot+Jpa多数据源配置的完整步骤  # spring基于通用Dao的多数据源配置详解  # Servlet+MyBatis项目转Spring Cloud微服务  # 多数据源配置修改建议  # Spring Boot 2.0多数据源配置方法实例详解  # spring多数据源配置实现方法实例分析  # 多个  # 都是  # 让人  # 尤其是  # 死了  # 只需  # 要在  # 而不  # 不符合  # 所示  # 再多  # 经常会  # 绑定  # 图中  # 配置文件  # 出在  # 大家多多  # 可看  # 上图  # 这并 


相关文章: 详解jQuery中基本的动画方法  宁波自助建站系统如何快速打造专业企业网站?  php json中文编码为null的解决办法  音响网站制作视频教程,隆霸音响官方网站?  厦门模型网站设计制作公司,厦门航空飞机模型掉色怎么办?  高配服务器限时抢购:企业级配置与回收服务一站式优惠方案  江苏网站制作公司有哪些,江苏书法考级官方网站?  如何选择建站程序?包含哪些必备功能与类型?  如何高效搭建专业期货交易平台网站?  魔毅自助建站系统:模板定制与SEO优化一键生成指南  IOS倒计时设置UIButton标题title的抖动问题  公司门户网站制作公司有哪些,怎样使用wordpress制作一个企业网站?  php能控制zigbee模块吗_php通过串口与cc2530 zigbee通信【介绍】  广州美橙建站如何快速搭建多端合一网站?  建站与域名管理如何高效结合?  建站之星好吗?新手能否轻松上手建站?  如何通过可视化优化提升建站效果?  如何在阿里云香港服务器快速搭建网站?  c# await 一个已经完成的Task会发生什么  威客平台建站流程解析:高效搭建教程与设计优化方案  如何通过虚拟机搭建网站?详细步骤解析  php条件判断怎么写_ifelse和switchcase的使用区别【对比】  深圳企业网站制作设计,在深圳如何网上全流程注册公司?  网站好制作吗知乎,网站开发好学吗?有什么技巧?  阿里云高弹*务器配置方案|支持分布式架构与多节点部署  企业宣传片制作网站有哪些,传媒公司怎么找企业宣传片项目?  如何解决ASP生成WAP建站中文乱码问题?  网站制作费用多少钱,一个网站的运营,需要哪些费用?  如何在万网开始建站?分步指南解析  定制建站如何定义?其核心优势是什么?  电视网站制作tvbox接口,云海电视怎样自定义添加电视源?  建站之星后台密码遗忘或太弱?如何重置与强化?  如何用花生壳三步快速搭建专属网站?  Python如何创建带属性的XML节点  移民网站制作流程,怎么看加拿大移民官网?  如何用西部建站助手快速创建专业网站?  非常酷的网站设计制作软件,酷培ai教育官方网站?  建站之星代理如何优化在线客服效率?  如何构建满足综合性能需求的优质建站方案?  香港服务器建站指南:免备案优势与SEO优化技巧全解析  如何快速查询域名建站关键信息?  陕西网站制作公司有哪些,陕西凌云电器有限公司官网?  如何在服务器上配置二级域名建站?  建站主机是否属于云主机类型?  电商网站制作公司有哪些,1688网是什么意思?  外贸公司网站制作哪家好,maersk船公司官网?  如何高效生成建站之星成品网站源码?  济南网站制作的价格,历城一职专官方网站?  高端云建站费用究竟需要多少预算?  已有域名和空间,如何快速搭建网站? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。