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">
&lt;!&ndash; 基本属性 url、user、password &ndash;&gt;
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" /> &lt;!&ndash; 配置初始化大小、最小、最大 &ndash;&gt;
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" /> &lt;!&ndash; 配置获取连接等待超时的时间 &ndash;&gt;
<property name="maxWait" value="60000" /> &lt;!&ndash; 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 &ndash;&gt;
<property name="timeBetweenEvictionRunsMillis" value="60000" /> &lt;!&ndash; 配置一个连接在池中最小生存的时间,单位是毫秒 &ndash;&gt;
<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" /> &lt;!&ndash; 打开PSCache,并且指定每个连接上PSCache的大小 &ndash;&gt;
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> &lt;!&ndash; 打开removeAbandoned功能 &ndash;&gt;
<property name="removeAbandoned" value="true" />
&lt;!&ndash; 1800秒,也就是30分钟 &ndash;&gt;
<property name="removeAbandonedTimeout" value="1800" />
&lt;!&ndash; 关闭abanded连接时输出错误日志 &ndash;&gt;
<property name="logAbandoned" value="true" /> &lt;!&ndash; 配置监控统计拦截的filters &ndash;&gt;
<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不同数据库数据源动态切换的更多相关文章

  1. spring+mybatis多数据源动态切换

    spring mvc+mybatis+多数据源切换 选取oracle,mysql作为例子切换数据源.oracle为默认数据源,在测试的action中,进行mysql和oracle的动态切换. web. ...

  2. Spring多数据源动态切换

    title: Spring多数据源动态切换 date: 2019-11-27 categories: Java Spring tags: 数据源 typora-root-url: ...... --- ...

  3. 实战:Spring AOP实现多数据源动态切换

    需求背景 去年底,公司项目有一个需求中有个接口需要用到平台.算法.大数据等三个不同数据库的数据进行计算.组装以及最后的展示,当时这个需求是另一个老同事在做,我只是负责自己的部分. 直到今年回来了,这个 ...

  4. Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源 方法

    一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...

  5. Springboot多数据源配置--数据源动态切换

    在上一篇我们介绍了多数据源,但是我们会发现在实际中我们很少直接获取数据源对象进行操作,我们常用的是jdbcTemplate或者是jpa进行操作数据库.那么这一节我们将要介绍怎么进行多数据源动态切换.添 ...

  6. springboot多数据源动态切换和自定义mybatis分页插件

    1.配置多数据源 增加druid依赖 完整pom文件 数据源配置文件 route.datasource.driver-class-name= com.mysql.jdbc.Driver route.d ...

  7. Spring3.3 整合 Hibernate3、MyBatis3.2 配置多数据源/动态切换数据源方法

    一.开篇 这里整合分别采用了Hibernate和MyBatis两大持久层框架,Hibernate主要完成增删改功能和一些单一的对象查询功能,MyBatis主要负责查询功能.所以在出来数据库方言的时候基 ...

  8. mybatis 多数据源动态切换

    笔者主要从事c#开发,近期因为项目需要,搭建了一套spring-cloud微服务框架,集成了eureka服务注册中心. gateway网关过滤.admin服务监控.auth授权体系验证,集成了redi ...

  9. Spring + Mybatis 项目实现动态切换数据源

    项目背景:项目开发中数据库使用了读写分离,所有查询语句走从库,除此之外走主库. 最简单的办法其实就是建两个包,把之前数据源那一套配置copy一份,指向另外的包,但是这样扩展很有限,所有采用下面的办法. ...

随机推荐

  1. Qt Creater中Clang-format的使用

    起因在于习惯性的想格式化代码,发现Qt Creater默认居然是没有代码格式化的,只有一个缩进,搞毛线啊!!! 搜索了下,倒是很容易就搜到了,Qt Creater中有个插件:beautifier,在 ...

  2. 【转载】C#进阶系列——动态Lamada(二:优化)

    前言:前几天写了一篇动态Lamada的文章C#进阶系列——动态Lamada,受园友xiao99的启发,今天打算来重新优化下这个动态Lamada的工具类.在此做个笔记,以免以后忘了. 一.原理分析 上篇 ...

  3. put ListView in a ScrollView(bug fixed)

    Android: put ListView in a ScrollView   When I need to use ListView with other controls on the same ...

  4. Surfer 高并发双核无头浏览器 (Golang语言)

    Surfer   A high level concurrency downloader. surfer是一款Go语言编写的高并发爬虫下载器,拥有surf与phantom两种下载内核. 支持固定Use ...

  5. sublime text 删除插件

    1.ctrl+shift+p 输入remove package 选择要删掉的插件即可 2.去掉产生临死文件的插件:phptools

  6. Oracle查询优化-使用字符串

    --1.遍历字符串 --1.1.建立测试视图 CREATE OR REPLACE VIEW V AS SELECT '天天向上' AS 汉字,'TTXS' AS 首拼 FROM DUAL; --要求每 ...

  7. 第五章 使用 SqlSession(MyBatis)

    在 MyBatis 中,你可以使用 SqlSessionFactory 来创建 SqlSession.一旦你获得一个 session 之后,你可以使用它来执行映射语句,提交或回滚连接,最后,当不再需要 ...

  8. vue实现图片点击放大

    用的vue-cli开发的项目,下面是具体实现代码 子组件: <template> <!-- 过渡动画 --> <transition name="fade&qu ...

  9. scala的基础部分

    最近接触到spark,spark又是scala编写的,所以需要学习一下scala. scala是面向对象的,一切皆为对象, 数值,函数都是对象. println("Welcome to th ...

  10. Python 调用外部命令

    python 可以使用 os 模块来调用外部的 Linux Shell 命令,常用的方法如下: os.system():结果输出在终端上,捕获不到os.popen() : 结果返回一个对象,即标准输出 ...