springMVC+Mybatis(使用AbstractRoutingDataSource实现多数据源切换时)事务管理未生效的解决办法
业务场景:
A、B两个单位,系统部署同一套代码;
A、B两系统能相互访问;
要求将数据从A系统同步到B系统,再将反馈信息回发给A;
实际开发情况:
因为系统比较小,最开始设计架构的时候没有考虑到消息互通的方式,也没有设计分布式部署,所以采用AbstractRoutingDataSource灵活切换数据源的方式直接在业务代码中实现数据交互。
项目代码:
applicationContext-common.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:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" 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/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:component-scan base-package="com.fms;com.job;com.jmda;">
<context:exclude-filter type="regex" expression=".controller.*"/>
</context:component-scan>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPaths">
<list>
<value>/WEB-INF/pages/</value>
<value>/WEB-INF/template/</value>
<value>classpath:/jmda-ftl/</value>
</list>
</property>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="number_format">0.##########</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="classic_compatible">true</prop>
<prop key="template_exception_handler">ignore</prop>
</props>
</property>
</bean> <!-- 配置c3p0数据源 -->
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="jdbcUrl">
<value><![CDATA[jdbc:mysql://192.168.5.186:3306/fms-ybj?useUnicode=yes&characterEncoding=UTF8]]></value>
</property>
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="maxPoolSize" value="200" />
<property name="minPoolSize" value="1" />
<property name="initialPoolSize" value="1" />
<property name="maxIdleTime" value="30" />
<property name="acquireIncrement" value="5" />
<property name="maxStatements" value="0" />
<property name="idleConnectionTestPeriod" value="60" />
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="true" />
<property name="testConnectionOnCheckout" value="false" />
</bean>
<bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="jdbcUrl">
<value><![CDATA[jdbc:mysql://192.168.5.186:3306/fms-zhs?useUnicode=yes&characterEncoding=UTF8]]></value>
</property>
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="maxPoolSize" value="200" />
<property name="minPoolSize" value="1" />
<property name="initialPoolSize" value="1" />
<property name="maxIdleTime" value="30" />
<property name="acquireIncrement" value="5" />
<property name="maxStatements" value="0" />
<property name="idleConnectionTestPeriod" value="60" />
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="true" />
<property name="testConnectionOnCheckout" value="false" />
</bean> <bean id="multipleDataSource" class="com.fms.common.datasource.MultipleDataSource">
<property name="defaultTargetDataSource" ref="dataSource1"/>
<property name="targetDataSources">
<map>
<entry key="dataSource1" value-ref="dataSource1"/>
<entry key="dataSource2" value-ref="dataSource2"/>
</map>
</property>
</bean>
<bean id="msqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="multipleDataSource"/>
<property name="configLocation" value="classpath:mybatis.xml" />
<property name="mapperLocations">
<list>
<value>classpath*:/com/fms/**/dao/*Mapper.xml</value>
<value>classpath*:/com/fms/**/dao/*DAO.xml</value>
</list>
</property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.fms.**.dao" />
<property name="sqlSessionFactory" ref="msqlSessionFactory" />
</bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="multipleDataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 文件上传配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000"/>
<property name="maxInMemorySize" value="10240000" />
</bean> </beans>
springmvc-servlet.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:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
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-4.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"> <context:component-scan base-package="com.fms;com.job;com.jmda;" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=UTF-8"></property>
<property name="requestContextAttribute" value="request" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
</bean>
<mvc:resources mapping="/static/**" location="/static/" />
<mvc:resources mapping="/jmda-static/**" location="/jmda-static/" />
<mvc:resources mapping="/assets/**" location="/assets/" /> <mvc:interceptors>
<bean class="com.fms.common.listener.SecurityInterceptor"/>
</mvc:interceptors>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/spring/applicationContext*.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</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>UTF-8</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <servlet>
<servlet-name>spring4mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring4mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>com.fms.common.listener.CommListener</listener-class>
</listener>
<!-- 400错误 -->
<error-page>
<error-code>400</error-code>
<location>/error</location>
</error-page>
<!-- 404 页面不存在错误 -->
<error-page>
<error-code>404</error-code>
<location>/error</location>
</error-page>
<!-- 403 服务器拒绝请求 -->
<error-page>
<error-code>403</error-code>
<location>/error</location>
</error-page>
<!-- 500 服务器内部错误 -->
<error-page>
<error-code>500</error-code>
<location>/error</location>
</error-page>
<!-- 503 服务不可用 -->
<error-page>
<error-code>503</error-code>
<location>/error</location>
</error-page>
<!-- java.lang.Exception -->
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error</location>
</error-page>
<!-- java.lang.NullPointerException -->
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/error</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/error</location>
</error-page>
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
</web-app>
MultipleDataSource:
package com.fms.common.datasource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class MultipleDataSource extends AbstractRoutingDataSource { private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>(); public static void setDataSourceKey(String dataSource) {
dataSourceKey.remove();
} public static void setDataSource(String dataSource){
dataSourceKey.remove();
dataSourceKey.set(dataSource);
}
public static String getKey(){
return dataSourceKey.get();
}
@Override
protected Object determineCurrentLookupKey() {
return dataSourceKey.get();
} }
简略的业务代码
@Transactional(rollbackFor = { Exception.class })
@Override
public void test() {
//默认数据源为datasource1 //do some SQL operate //切换数据源
MultipleDataSource.setDataSource("datasource2"); //do other SQL operate //…… ……
}
代码进行到上面的阶段,各项业务在正常情况下能够顺利执行,但是在发生异常时出现了事务无法回滚的情况,于是我在网上找各种方法尝试修改;
一开始我以为是AbstractRoutingDataSource多数据源的问题,一直从这方面找答案,找了很多例子修改后都仍然无法正常开启事务管理,偶然一次看到一个帖子讲spring父子容器配置,看完后照着改完,然后重新启动项目,结果真的成功了。
具体修改如下:
applicationContext-common.xml中:
<!--
<context:component-scan base-package="com.fms;com.job;com.jmda;">
<context:exclude-filter type="regex" expression=".controller.*"/>
</context:component-scan> --> 改为: <context:component-scan base-package="com.fms;com.job;com.jmda;">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
springmvc-servlet.xml中:
<!--
<context:component-scan base-package="com.fms;com.job;com.jmda;" />
--> 改为: <context:component-scan base-package="com.fms;com.job;com.jmda;" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
原因:
Spring容器优先加载由ServletContextListener(对应applicationContext.xml)产生的父容器,而SpringMVC(对应mvc_dispatcher_servlet.xml)产生的是子容器。子容器Controller进行扫描装配时装配的@Service注解的实例是没有经过事务加强处理,即没有事务处理能力的Service,而父容器进行初始化的Service是保证事务的增强处理能力的。如果不在子容器中将Service exclude掉,此时得到的将是原样的无事务处理能力的Service,因为在多上下文的情况下,如果同一个bean被定义两次,后面一个优先。
参考博文:http://blog.csdn.net/will_awoke/article/details/12002705
经过测试,发现了新的问题:
在做了上述处理之后,项目事务生效了,但是多数据源切换却出现问题不能切换了,DataSourceTransactionManager只能管理一个数据源的事务,如果想要实现动态切换数据源就需要放弃spring的事务管理,在网上找了很久终于找到了一个解决方案:atomikos+jta进行分布式事务管理。
参考博文:http://www.blogjava.net/zuxiong/archive/2015/09/24/427471.html
springMVC+Mybatis(使用AbstractRoutingDataSource实现多数据源切换时)事务管理未生效的解决办法的更多相关文章
- 【转】Android Fragment中使用SurfaceView切换时闪一下黑屏的解决办法
重构了下之前自己的一个新闻客户端,全部使用了Fragment来进行页面切换,只有一个入口Activity作为程序的启动Activity,其中有一个界面需要调用摄像头识别二维码, 于是就会用到Surfa ...
- [Android Pro] Fragment中使用SurfaceView切换时闪一下黑屏的解决办法
方法一.在Activity的onCreate中添加如下代码 getWindow().setFormat(PixelFormat.TRANSLUCENT); reference to : http:/ ...
- SpringMVC 利用AbstractRoutingDataSource实现动态数据源切换
SpringMVC 利用AbstractRoutingDataSource实现动态数据源切换 本文转载至:http://exceptioneye.iteye.com/blog/1698064 Spri ...
- AbstractRoutingDataSource 实现动态数据源切换原理简单分析
AbstractRoutingDataSource 实现动态数据源切换原理简单分析 写在前面,项目中用到了动态数据源切换,记录一下其运行机制. 代码展示 下面列出一些关键代码,后续分析会用到 数据配置 ...
- Spring Boot学习笔记(七)多数据源下的事务管理
DataBaseConfig中加入事务管理器 DataBaseConfig的详解以及多数据源的配置参见我的上一篇文章 @Configuration @MapperScan(basePackages={ ...
- spring+springMVC+Mybatis架构下采用AbstractRoutingDataSource、atomikos、JTA实现多数据源灵活切换以及分布式事务管理
背景: 1.系统采用SSM架构.需要在10多个MYSQL数据库之间进行切换并对数据进行操作,上篇博文<springMVC+Mybatis(使用AbstractRoutingDataSource实 ...
- SpringMVC+Mybatis 如何配置多个数据源并切换?
最近公司一个项目需要连接两个数据库(A和B)操作,有的模块查询A库,有的模块查询B库,因此需要改造下,项目后台用的是SpringMVC+Mybatis+MySQL架构,折腾了两天后终于搞定了,在这里记 ...
- AbstractRoutingDataSource实现动态数据源切换 专题
需求:系统中要实现切换数据库(业务数据库和his数据库) 网上很多资料上有提到AbstractRoutingDataSource,大致是这么说的 在Spring 2.0.1中引入了AbstractRo ...
- Spring(AbstractRoutingDataSource)实现动态数据源切换--转载
原始出处:http://linhongyu.blog.51cto.com/6373370/1615895 一.前言 近期一项目A需实现数据同步到另一项目B数据库中,在不改变B项目的情况下,只好选择项目 ...
随机推荐
- java源码剖析: 对象内存布局、JVM锁以及优化
一.目录 1.启蒙知识预热:CAS原理+JVM对象头内存存储结构 2.JVM中锁优化:锁粗化.锁消除.偏向锁.轻量级锁.自旋锁. 3.总结:偏向锁.轻量级锁,重量级锁的优缺点. 二.启蒙知识预热 开启 ...
- cookie方法封装及cookie缺点分析
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Consolas; color: #4f5d66 } p.p2 { margin: 0.0px ...
- 不须组件的NPOI插件 excel读取
前提: 需要DLL 1.引用 using NPOI.SS.UserModel; using NPOI.XSSF.UserModel;//用于2007版本 using NPOI.HSSF.UserMo ...
- split()方法
split()方法用于把一个字符串分隔成字符串数组. 它有两个参数: separator:从参数指定的地方分隔字符串,必需: howmany:该参数可指定返回的数组的最大长度.如果设置了该参数,返回的 ...
- poj2653线段相交判断
Stan has n sticks of various length. He throws them one at a time on the floor in a random way. Afte ...
- 再议Unity优化
0x00 前言 在很长一段时间里,Unity项目的开发者的优化指南上基本都会有一条关于使用GetCompnent方法获取组件的条目(例如14年我的这篇博客<深入浅出聊Unity3D项目优化:从D ...
- webstorm安装与本地激活
webstorm下载及安装 官方下载地址如下:https://www.jetbrains.com/webstorm/ 安装: 直接双击安装,注意路径中不要出现中文. 激活:(此方法来自网络) 许多人j ...
- 如何为mysql添加、启动服务
1.点击"开始",输入cmd,以管理员身份运行: 2.进入mysql的bin目录,执行 mysqld --install,然后执行 net start mysql :
- [刷题]算法竞赛入门经典(第2版) 6-8/UVa806 - Spatial Structures
题意:黑白图像的路径表示法 代码:(Accepted,0.120s) //UVa806 - Spatial Structures //Accepted 0.120s //#define _XIENAO ...
- Oracle 12C 新特性之move (非分区表)table online
以前版本中move table不能够online, move 会引rowid改变使对应的索引失效. 12c 中 alter table move online不会对新事务阻塞同时会自动的维护索引的有效 ...