SSM框架项目同时配置多个数据库连接

前言:

对于系统业务实现,经常需要连接多个数据库的情况,一般项目只配置了一个数据库,现通过查询资料探究项目同时连接多个数据库,在需要的时候进行灵活切换。

操作步骤:

1、db.properties文件配置修改(本次测试连接两个数据源)

ds1.jdbc.driver=com.mysql.jdbc.Driver
ds1.jdbc.url=jdbc\:mysql\://10.128.XX.XX\:3306/fdc?useUnicode\=true&characterEncoding\=utf-8
jdbc.username=Ov4j7fKiCzY=
jdbc.password=IL4H6kEmHOOAyXoBoTkTRQ==

ds2.jdbc.driver=com.mysql.jdbc.Driver
ds2.jdbc.url=jdbc\:mysql\://10.128.XX.XX\:3306/xemc-data?useUnicode\=true&characterEncoding\=utf-8

2、applicationContext.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util 
	http://www.springframework.org/schema/util/spring-util-4.0.xsd
	http://www.springframework.org/schema/cache  
	http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"
	>
	<!-- 扫描 service -->
   	<context:component-scan base-package="XXX.XXX"
		annotation-config="true">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>  
  
	<!-- 读取数据库配置文件 -->
	<bean class="XXXX" p:location="classpath:/db.properties"></bean>
	
	<!-- 数据库连接池   XXX.DynamicDataSource为第三步编写的类路径 -->
	<bean id="dynamicDataSource"  class="XXX.DynamicDataSource">
	    <property name="targetDataSources"> 
	       <map key-type="java.lang.String"> 
	       <!-- 指定lookupKey和与之对应的数据源 --> 
	           <entry key="ds1" value-ref="ds1"></entry> 
	           <entry key="ds2" value-ref="ds2"></entry> 
	       </map> 
	    </property> 
	    <!-- 这里可以指定默认的数据源 --> 
	    <property name="defaultTargetDataSource" ref="ds1" /> 
	</bean>

	
	
	<bean id="ds1" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${ds1.jdbc.driver}" />
		<property name="url" value="${ds1.jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>
	<bean id="ds2" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${ds2.jdbc.driver}" />
		<property name="url" value="${ds2.jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxActive" value="10" />
		<property name="maxIdle" value="5" />
	</bean>
	
	<!-- Mybatis的工厂 -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dynamicDataSource"/>
		<!-- 核心配置文件的位置 -->
		<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
	</bean>

	<!-- Mapper动态代理开发   扫描 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 基本包 -->
		<property name="basePackage" value="com.scada.springmvc.dao"/>
	</bean>
	
	<!-- 注解事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	  <!-- 配置为dynamicDataSource -->
	  <property name="dataSource" ref="dynamicDataSource"/>
	</bean>
	<!-- 开启注解 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- 缓存配置 -->
	<!-- 启用缓存注解功能(请将其配置在Spring主配置文件中) -->
	<cache:annotation-driven cache-manager="cacheManager" />
	
	<!-- Spring自己的基于java.util.concurrent.ConcurrentHashMap实现的缓存管理器(该功能是从Spring3.1开始提供的) -->
	<!-- <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> 
		<property name="caches"> <set> <bean name="myCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"/> 
		</set> </property> </bean> -->
	
	<!-- 若只想使用Spring自身提供的缓存器,则注释掉下面的两个关于Ehcache配置的bean,并启用上面的SimpleCacheManager即可 -->
	<!-- Spring提供的基于的Ehcache实现的缓存管理器 -->
	<bean id="cacheManagerFactory"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation" value="classpath:ehcache.xml" />
	</bean>
	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
		<property name="cacheManager" ref="cacheManagerFactory" />
	</bean>

</beans>

3、获取当前使用的数据源

package xxx;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 
/**
 * Created by Robin on 2019-02-13.
 */ 
    public class DynamicDataSource extends AbstractRoutingDataSource { 
    /**
     * 取得当前使用那个数据源。
     */ @Override protected Object determineCurrentLookupKey() {
    	 return DbContextHolder.getDbType(); 
    	 } 
     }

4、切换数据源的工具类

package xxx;
/**
 * Created by Robin on 2019-02-13.
 */ 
public class DbContextHolder
{ 
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); 
	/**
     * 设置当前数据库。
     * @param dbType
     */ 
     public static void setDbType(String dbType) { 
    	 contextHolder.set(dbType); 
    	 } 
     /**
     * 取得当前数据源。
     * @return
     */ 
     public static String getDbType() { 
    	 String str = (String) contextHolder.get(); 
    	 return str; 
    	 } 
     /**
     * 清除上下文数据
     */ 
     public static void clearDbType() { 
    	 contextHolder.remove(); 
     } 
     
}


5、在控制层进行业务调用

        //数据源切换
		DbContextHolder.setDbType("ds2");
		UserInfo userinfo = userLoginService.login(user);

结果:

登录成功
在这里插入图片描述

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
SSM框架中同时连接两个数据库,可以按照以下步骤进行: 1. 在applicationContext.xml配置文件中,配置两个数据源。例如: ``` <bean id="dataSource1" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db1"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db2"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> ``` 2. 在MyBatis的Mapper映射文件中,使用<sqlSessionTemplate>标签配置两个SqlSessionTemplate。例如: ``` <bean id="sqlSessionTemplate1" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory1"/> </bean> <bean id="sqlSessionTemplate2" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory2"/> </bean> ``` 其中,sqlSessionFactory1和sqlSessionFactory2分别是两个数据源对应的SqlSessionFactory。 3. 在需要使用的Mapper接口中,使用@Qualifier注解指定使用哪个SqlSessionTemplate。例如: ``` @Autowired @Qualifier("sqlSessionTemplate1") private SqlSessionTemplate sqlSessionTemplate1; @Autowired @Qualifier("sqlSessionTemplate2") private SqlSessionTemplate sqlSessionTemplate2; ``` 这样,在使用Mapper接口时,就可以通过sqlSessionTemplate1和sqlSessionTemplate2分别操作两个数据库了。 需要注意的是,使用多个数据源会增加系统的复杂度和维护成本,因此需要根据实际情况进行评估和选择。同时,使用多个数据源时需要注意事务的控制,确保事务的一致性。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值