170615、spring不同数据库数据源动态切换
spring mvc+mybatis+多数据源切换 选取Oracle,MySQL作为例子切换数据源。mysql为默认数据源,在测试的action中,进行mysql和oracle的动态切换。
1、web.xml配置
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>trac</param-value>
</context-param> <!-- Spring的log4j监听器 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> <!-- 字符集 过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- Spring view分发器 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2、dispatcher.xm
<mvc:annotation-driven />
<context:component-scan base-package="com.trac" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> <!-- freemarker config -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
<property name="freemarkerSettings">
<props>
<prop key="defaultEncoding">UTF-8</prop>
</props>
</property>
</bean> <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" /> <!-- View resolvers can also be configured with ResourceBundles or XML files.
If you need different view resolving based on Locale, you have to use the
resource bundle resolver. -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
</bean>
3、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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"></bean> <bean id="mySqlDataSource" parent="parentDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/icbc_wx"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean> <bean id="oracleDataSource" parent="parentDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@192.168.1.168:1521:orcl"></property>
<property name="username" value="zcgd"></property>
<property name="password" value="zcgd"></property>
</bean> <!--多数据源-->
<bean id="dataSource" class="com.strongunion.common.datasource.DataSources">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="mySqlDataSource" key="MYSQL"></entry>
<entry value-ref="oracleDataSource" key="ORACLE"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="mySqlDataSource"></property>
</bean> <!--单一数据源-->
<!--<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!– 基本属性 url、user、password –>
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" /> <!– 配置初始化大小、最小、最大 –>
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" /> <!– 配置获取连接等待超时的时间 –>
<property name="maxWait" value="60000" /> <!– 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 –>
<property name="timeBetweenEvictionRunsMillis" value="60000" /> <!– 配置一个连接在池中最小生存的时间,单位是毫秒 –>
<property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" /> <!– 打开PSCache,并且指定每个连接上PSCache的大小 –>
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!– 打开removeAbandoned功能 –>
<property name="removeAbandoned" value="true" />
<!– 1800秒,也就是30分钟 –>
<property name="removeAbandonedTimeout" value="1800" />
<!– 关闭abanded连接时输出错误日志 –>
<property name="logAbandoned" value="true" /> <!– 配置监控统计拦截的filters –>
<property name="filters" value="stat" />
</bean>--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" /> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
</beans>
4、DataSourceInstances.java
package com.strongunion.common.datasource; /**
* Desc : 定义数据源的标识, 和applicationContext.xml中 DataSources 的 targetDataSources 的key对应
* User : RICK
* Time : 2017/8/18 9:41
*/ public class DataSourceInstances {
/**mysql数据源*/
public static final String MYSQL="MYSQL";
/**oralce数据源*/
public static final String ORACLE="ORACLE";
}
5、DataSourceSwitch.java
package com.strongunion.common.datasource; /**
* Desc : 切换数据源开关
* User : RICK
* Time : 2017/8/18 10:49
*/ public class DataSourceSwitch { private static final ThreadLocal contextHolder=new ThreadLocal(); public static void setDataSourceType(String dataSourceType){
contextHolder.set(dataSourceType);
} public static String getDataSourceType(){
return (String) contextHolder.get();
} public static void clearDataSourceType(){
contextHolder.remove();
}
}
6、DataSources.java
package com.strongunion.common.datasource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; /**
* Desc : 配置于applicationContext 中,线程局部变量ThreadLocal contextHolder
* 保存当前需要的数据源类型,当 DataSourceSwitch. setDataSourceType(DataSourceInstances.XXX)
* 保存当前需要的数据源类型的时候,DataSources 会从当前线程中查找线程变量的数据源类型,从而决定使用何种数据源
* User : RICK
* Time : 2017/8/18 9:43
*/ public class DataSources extends AbstractRoutingDataSource { @Override
protected Object determineCurrentLookupKey() {
return DataSourceSwitch.getDataSourceType();
}
}
7、测试类TestController.java
package com.strongunion.apps.controller; import com.strongunion.apps.service.IUserService;
import com.strongunion.common.ResultJson;
import com.strongunion.common.datasource.DataSourceInstances;
import com.strongunion.common.datasource.DataSourceSwitch;
import com.strongunion.generator.entity.User;
import com.strongunion.utils.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource;
import java.util.List; /**
* Desc : 测试数据源
* User : RICK
* Time : 2017/8/18 9:27
*/ @RestController
@RequestMapping("/demo")
public class TestController { private static final Logger log = LoggerFactory.getLogger(TestController.class); @Resource
private IUserService userService; @RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(){
return "hello";
} @RequestMapping(value = "/db/{type}", method = RequestMethod.GET)
public ResultJson testDataBase(@PathVariable("type") String type) throws Exception{
ResultJson resultJson = null;
if (Util.isNotNull(type)){
if(DataSourceInstances.MYSQL.equals(type)){
DataSourceSwitch.setDataSourceType(DataSourceInstances.MYSQL);
} else if(DataSourceInstances.ORACLE.equals(type)){
DataSourceSwitch.setDataSourceType(DataSourceInstances.ORACLE);
}
} else {
DataSourceSwitch.setDataSourceType(DataSourceInstances.MYSQL);
}
List<User> userList = userService.queryAllUsers();
log.info("userList------------------------------>" + userList);
resultJson = ResultJson.buildSuccessInstance(userList);
return resultJson;
}
}
8、运行效果
mysql数据库

oralce数据库

mysql数据源

oracle数据源

170615、spring不同数据库数据源动态切换的更多相关文章
- spring+mybatis多数据源动态切换
spring mvc+mybatis+多数据源切换 选取oracle,mysql作为例子切换数据源.oracle为默认数据源,在测试的action中,进行mysql和oracle的动态切换. web. ...
- Spring多数据源动态切换
title: Spring多数据源动态切换 date: 2019-11-27 categories: Java Spring tags: 数据源 typora-root-url: ...... --- ...
- 实战:Spring AOP实现多数据源动态切换
需求背景 去年底,公司项目有一个需求中有个接口需要用到平台.算法.大数据等三个不同数据库的数据进行计算.组装以及最后的展示,当时这个需求是另一个老同事在做,我只是负责自己的部分. 直到今年回来了,这个 ...
- Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源 方法
一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...
- Springboot多数据源配置--数据源动态切换
在上一篇我们介绍了多数据源,但是我们会发现在实际中我们很少直接获取数据源对象进行操作,我们常用的是jdbcTemplate或者是jpa进行操作数据库.那么这一节我们将要介绍怎么进行多数据源动态切换.添 ...
- springboot多数据源动态切换和自定义mybatis分页插件
1.配置多数据源 增加druid依赖 完整pom文件 数据源配置文件 route.datasource.driver-class-name= com.mysql.jdbc.Driver route.d ...
- Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源方法
一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...
- mybatis 多数据源动态切换
笔者主要从事c#开发,近期因为项目需要,搭建了一套spring-cloud微服务框架,集成了eureka服务注册中心. gateway网关过滤.admin服务监控.auth授权体系验证,集成了redi ...
- Spring + Mybatis 项目实现动态切换数据源
项目背景:项目开发中数据库使用了读写分离,所有查询语句走从库,除此之外走主库. 最简单的办法其实就是建两个包,把之前数据源那一套配置copy一份,指向另外的包,但是这样扩展很有限,所有采用下面的办法. ...
随机推荐
- QSignalMapper Class
/************************************************************************************** * QT QSignal ...
- [转载] PHP开发必看 编程十大好习惯
适当抽象 但是在抽象的时候,要避免不合理的抽象,有时也可能造成过渡设计,现在只需要一种螺丝刀,但你却把更多类型的螺丝刀都做出来了(而且还是瑞士军刀的样子..): 一致性 团队开发中,可能每个人的编程风 ...
- e575. The Quintessential Drawing Program
To draw on the screen, it is first necessary to subclass a JComponent and override its paint() metho ...
- 基于<最简单的基于FFMPEG+SDL的视频播放器 ver2 (采用SDL2.0)>的一些个人总结
最近因为项目接近收尾阶段,所以变的没有之前那么忙了,所以最近重新拿起了之前的一些FFMPEG和SDL的相关流媒体播放器的例子在看. 同时自己也用FFMPEG2.01,SDL2.01结合MFC以及网上罗 ...
- linux -- 修改文件
vi编辑器有三种模式:命令模式,编辑模式,末行模式 打开vi后首先是命令模式,用i,o,a等进入编辑模式, 按esc退出编辑模式,回到命令模式. 在命令模式下输入:wq表示保存退出,:wq!强制保存退 ...
- write solid code 零散(原文)
整理下目录,看了这个文件,幸好未删除. 以下是<write solid code>中的原文摘录. 1.How could I have prevented this bug? 2.How ...
- easyUI实现(alert)提示框自动关闭的实例代码
function alert_autoClose(title,msg,icon){ var interval; var time=1000; var x=2; //设置时间2s $.messa ...
- 怎样用MathType创建竖式算法
在使用MathType编辑公式时,有时将最简单的表达式变成Word文档也会出现一些问题.比如MathType竖式.下面介绍MathType竖式的一些编辑方法. 步骤如下: 步骤一:在MathType底 ...
- LLE局部线性嵌入算法
非线性降维 流形学习 算法思想有些类似于NLM,但是是进行的降维操作. [转载自] 局部线性嵌入(LLE)原理总结 - yukgwy60648的博客 - CSDN博客 https://blog.csd ...
- VC++ ToolTip的简单使用
1.在基于对话框的MFC应用程序中使用Tooltip,首先在Dlg类的头文件中定义一个变量: CToolTipCtrl m_iToolTips; 2.在Dlg类的OnInitDialog中添加代码: ...