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. Java 二维码--转载

    周末试用下Android手机的二维码扫描软件,扫描了下火车票.名片等等,觉得非常不错很有意思的.当然Java也可以实现这些,现在就分享下如何简单用Java实现二维码中QRCode的编码和解码(可以手机 ...

  2. 【转】DirectorySearcher.Filter属性说明

    DirectorySearcher.Filter属性扩充申明 DirectorySearcher mySearcher = new DirectorySearcher(entryOU, "( ...

  3. Kernel.org 被黑,获取 Android 源码方法一则

    8 月底 9 月初,作为 Linux 的老窝,Kernel.org 被黑客攻击了,其攻击原因众说纷纭.一直以来 Linux 对于我来说不是很感兴趣,所以从来不会关注类似事件,可是这次这个攻击,却影响到 ...

  4. PHP清除HTML代码、空格、回车换行符的函数

    清除HTML代码.空格.回车换行符的函数如下 function DeleteHtml($str) { $str = trim($str); $str = strip_tags($str,"& ...

  5. PHP curl_setopt函数用法介绍上篇

    最近,学习与实践了php中curl的知识点.在此做个初步的总结: 先看看对于它的基本介绍: curl_setopt函数是php中一个重要的函数,它可以模仿用户的一些行为,如模仿用户登录,注册等等一些用 ...

  6. c++ time_t

    type struct tm <ctime> Time structure Structure containing a calendar date and time broken dow ...

  7. BIEE物理业务层编辑之后发布路径

    在BI 业务逻辑层编辑之后,需要发布,地址是http://pc201411260149:7001/em/, IP/em 在business intelligence 页面,点击部署,然后选择文件发布

  8. <OC>OC新特征array literals

    类似于java5提供的autoboxing功能.以前的写法:NSNumber * number = [NSNumber numberWithInt:1];NSArray * array = [NSAr ...

  9. linux下如何关闭防火墙、查看当前的状态、开放端口

    从配置菜单关闭防火墙是不起作用的,索性在安装的时候就不要装防火墙查看防火墙状态:/etc/init.d/iptables status暂时关闭防火墙:/etc/init.d/iptables stop ...

  10. jQuery对象的链式操作用法分析

    可以使用下面的原则判断一个函数返回的时候是jQuery对象,即是否可以用于链式操作. 除了获取某些数据的函数,比如获取属性值"attr(name)",获取集合大小"siz ...