一、知識點及問題
後端框架:
Spring 、Spring mvc 、mybatis
業務需求:
客戶端先從服務端獲取用戶大量信息到客戶端,編輯完成之後統一Post至服務端,對於數據的修改要麼全成功,要麼全失敗,所以需要使用事務支持。
問題:
配置Spring聲明式事務,執行中出現異常未回滾.從網上查詢得到一開始是自己的配置出了問題,由於配置文件的加載順序決定了容器的加載順序導致Spring事務沒有起作用。詳情如下:
由於採用的是SpringMVC、 MyBatis,故統一採用了標註來聲明Service、Controller
由於服務器啓動時的加載配置文件的順序爲web.xml—root-context.xml(Spring的配置文件)—servlet-context.xml(SpringMVC的配置文件),由於root-context.xml配置文件中Controller會先進行掃描裝配,但是此時service還沒有進行事務增強處理,得到的將是原樣的Service(沒有經過事務加強處理,故而沒有事務處理能力),所以我們必須在root-context.xml中不掃描Controller
上面的問題解決後還是沒有回滾,後來瞭解到,Spring 只會在程序執行中出現unchecked(RuntimeException)的異常時纔會觸發回滾。由於是與客戶端直接交互的Server所以要將每一個處理結果以 errorcode 錯誤碼和msg 錯誤信息的形式反饋給客戶端所以顯式捕捉了所有的異常,並將信息以Json數據格式發送給客戶端這才導致了出現異常時事務沒有回滾。
因爲要給客戶端最真實、準確的錯誤信息反饋又不得不捕捉可能發生的異常又陷入了沉思.當然,問題總是有解決的方式的,哪怕是繞着走。之後從查詢資料得到,捕捉可以,但是捕捉之後主動拋出還是會引發事務回滾的!(喜)然後就想到在主動 throw new RuntimeException(“反饋給客戶端的信息”);將要反饋給客戶端的具體錯誤信息包裝到異常信息中,發生異常時在Controller層catch異常,將信息返回至客戶端。
(mysql 表的engine爲InnoDB–支持事務回滾,默認爲MyISAM–效率高)
到此,問題解決。
二、案例聲明
崗位: Java服務端
工作內容: 接收來自客戶端的請求(android,androidtv,ios,pc ..),對客戶端請求數據做合法性校驗,並與其他服務端交互獲取客戶端所需數據。
三、代碼及配置
1.web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
2. Spring-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 配置註解掃描,掃描 Controller層不掃描Service層 -->
<context:component-scan base-package="cn.com.XX">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
</beans>
3. mybatis-config.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- changes from the defaults for testing -->
<setting name="cacheEnabled" value="true" />
<setting name="useGeneratedKeys" value="true" />
<setting name="defaultExecutorType" value="REUSE" />
<!-- <setting name="logImpl" value="LOG4J"/> -->
</settings>
<!-- mybatis分頁插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql" />
</plugin>
</plugins>
</configuration>
4. 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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<!--加載配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:system.properties" />
</bean>
<!--配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver">
</property>
<property name="jdbcUrl"
value="${數據庫連接}">
</property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<!--連接池中保留的最大連接數。Default: 15 -->
<property name="maxPoolSize" value="15"></property>
<!--連接池中保留的最小連接數。 -->
<property name="minPoolSize" value="3"></property>
<!--初始化時獲取的連接數,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--最大空閒時間,20秒內未使用則連接被丟棄。若爲0則永不丟棄。Default: 0 -->
<property name="maxIdleTime" value="20"></property>
<!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 -->
<property name="acquireIncrement">
<value>5</value>
</property>
<!-- JDBC的標準參數,用以控制數據源內加載的PreparedStatements數量。但由於預緩存的statements 屬於單個connection而不是整個連接池。所以設置這個參數需要考慮到多方面的因素。
如果maxStatements與maxStatementsPerConnection均爲0,則緩存被關閉。Default: 0 -->
<property name="maxStatements">
<value>0</value>
</property>
<!--每60秒檢查所有連接池中的空閒連接。Default: 0 -->
<property name="idleConnectionTestPeriod">
<value>60</value>
</property>
<!--定義在從數據庫獲取新連接失敗後重復嘗試的次數。Default: 30 -->
<property name="acquireRetryAttempts">
<value>30</value>
</property>
<!-- 獲取連接失敗將會引起所有等待連接池來獲取連接的線程拋出異常。但是數據源仍有效 保留,並在下次調用getConnection()的時候繼續嘗試獲取連接。如果設爲true,那麼在嘗試
獲取連接失敗後該數據源將申明已斷開並永久關閉。Default: false -->
<property name="breakAfterAcquireFailure">
<value>true</value>
</property>
<!-- 因性能消耗大請只在需要的時候使用它。如果設爲true那麼在每個connection提交的 時候都將校驗其有效性。建議使用idleConnectionTestPeriod或automaticTestTable
等方法來提升連接測試的性能。Default: false -->
<property name="testConnectionOnCheckout">
<value>true</value>
</property>
</bean>
<!-- 註解掃描,不掃描Controller層 -->
<context:component-scan base-package="cn.com.xx">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:cn/com/xx/**/*.xml" />
</bean>
<!-- yxt add -->
<bean id="mapperScanneryxt" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.com.xx.mapper" />
</bean>
<!--配置事務管理器 -->
<!-- transaction manager, use DataSourceTransactionManager -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 切面 -->
<aop:config>
<aop:pointcut id="fooServiceMethods"
expression="execution(* cn.com.xx.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods" />
</aop:config>
<!--通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="select*" read-only="true" />
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
</beans>
5. 代碼示例
Service業務邏輯處理層
try {
log.info("check phone is exist before ..");
int count = tMailingMapper.insert(record);
if (count > 0) {
log.info("添加 " + accountid + " 的好友"
+ account.getAccountid() + " "
+ phoneVo.getRemark() + " 成功");
} else {
log.info("添加 " + accountid + " 的好友"
+ account.getAccountid() + " "
+ phoneVo.getRemark() + " 失敗");
}
} catch (Exception e) {
log.error("添加聯繫人出現了異常 " + e.getMessage());
resJson.put("errorcode", "20022");
resJson.put("msg", "同步信息異常,請稍後重試");
throw new RuntimeException(resJson.toString());
}
Controller 控制層
@RequestMapping("/update/userinfo")
public String updateUserInfo(HttpServletRequest request, HttpServletResponse response) {
log.info("update userInfo start ..");
String resText=null;
try {
resText = userService.updateUserInfo(request);
} catch (Exception e) {
log.error("更新信息失敗,事務已回滾...",e);
resText=e.getMessage();
}
<-- 將操作結果返回給client-->
HttpsUtil.sendAppMessage(resText, response);
return null;
}
本人初入Java,小白一枚,有不到之處還請見諒。歡迎大神指點!
2016-03-19 10:58:58
參考文章:1. http://sence-qi.iteye.com/blog/1328902/
2.http://blog.sina.com.cn/s/blog_89ca421401016bmg.html