spring mvc 多數據源切換,不支持事務控制[一]

来源:http://www.cnblogs.com/eastday/archive/2017/09/28/7608455.html
-Advertisement-
Play Games

一個項目中需要使用兩個資料庫,Oracle 和Mysql ,於是參考各個blog,實現此功能.寫好後才發現,原來的事務失效了,我去... spring-mybatis.xml 配置 @Documented @Retention(RetentionPolicy.RUNTIME) @Target({El ...


一個項目中需要使用兩個資料庫,Oracle 和Mysql ,於是參考各個blog,實現此功能.寫好後才發現,原來的事務失效了,我去...

spring-mybatis.xml 配置

    <bean id="configReader" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:spring/db.properties</value>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.oracle.DriverClassName}"></property>
        <property name="jdbcUrl" value="${jdbc.oracle.Url}"></property>
        <property name="user" value="${jdbc.oracle.UserName}"></property>
        <property name="password" value="${jdbc.oracle.UserPassword}"></property>

        <property name="acquireIncrement" value="5"></property>
        <property name="initialPoolSize" value="5"></property>
        <property name="maxIdleTime" value="60"></property>
        <property name="maxPoolSize" value="100"></property>
        <property name="minPoolSize" value="5"></property>
    </bean>


    <!-- 配置數據源:MySQL start -->
    <bean name="mySqlDataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.mysql.DriverClassName}"/>
        <property name="url" value="${jdbc.mysql.Url}"/>
        <property name="username" value="${jdbc.mysql.UserName}"/>
        <property name="password" value="${jdbc.mysql.UserPassword}"/>

        <!-- 初始化連接大小 -->
        <property name="initialSize" value="5"/>
        <!-- 連接池最大使用連接數量 -->
        <property name="maxActive" value="30"/>
        <!-- 連接池最小空閑 -->
        <property name="minIdle" value="2"/>
        <!-- 獲取連接最大等待時間 -->
        <property name="maxWait" value="300"/>

        <property name="validationQuery" value="SELECT 1"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="testWhileIdle" value="true"/>

        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="10000"/>
        <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="30000"/>

        <!-- 打開removeAbandoned功能 -->
        <property name="removeAbandoned" value="true"/>
        <!-- 1800秒,也就是30分鐘 -->
        <property name="removeAbandonedTimeout" value="1800"/>
        <!-- 關閉abanded連接時輸出錯誤日誌 -->
        <property name="logAbandoned" value="true"/>

        <!-- 監控資料庫 -->
        <property name="filters" value="stat"/>
    </bean>


    <bean id="multipleDataSource" class="com.we.database.MultipleDataSource">
        <property name="defaultTargetDataSource" ref="dataSource"/>
        <property name="targetDataSources">
            <map>
                <entry key="oracleDataSource" value-ref="dataSource"/>
                <entry key="mySqlDataSource" value-ref="mySqlDataSource"/>
            </map>
        </property>
    </bean>

    <!-- oracle myBatis file -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="multipleDataSource"/>
        <!--<property name="configLocation" value="classpath:configuration.xml" /> -->
        <property name="mapperLocations" value="classpath:com/we/dao/mapper/*.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.we.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>


    <!-- configure transaction -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- annotation transaction -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>


    <!-- interception transatcion -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置資料庫註解aop -->
    <bean id="dataSourceAspect" class="com.we.database.DataSourceAspect"/>

    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com.wewe.licai.service..*Impl.*(..))"/>
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" order="2"/>

        <!--數據源選擇切麵,保證在事務開始之前執行-->
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="dataSourceAspect"  order="1" />
    </aop:config>
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})

public @interface DataSource {
     String name() default DataSource.oracleDataSource;
     String mySqlDataSource = "mySqlDataSource";
     String oracleDataSource = "oracleDataSource";
}
註解切換,預設使用oracle數據源
/**
 * Created by eastday on 2017/9/21.
 */
public class DataSourceAspect implements MethodBeforeAdvice,AfterReturningAdvice
{

    @Override
    public void afterReturning(Object returnValue, Method method,
                               Object[] args, Object target) throws Throwable {

        MultipleDataSource.clearDataSource();
    }

    @Override
    public void before(Method method, Object[] args, Object target)
            throws Throwable {

        //首先取類上的數據源
        if(method.getDeclaringClass().isAnnotationPresent(DataSource.class) && !method.isAnnotationPresent(DataSource.class)) {

            DataSource datasource = method.getDeclaringClass().getAnnotation(DataSource.class);
            MultipleDataSource.setDataSource(datasource.name());

            //方法上的數據源 優先順序高於類上的
        } else if (method.isAnnotationPresent(DataSource.class)) {

            DataSource datasource = method.getAnnotation(DataSource.class);
            MultipleDataSource.setDataSource(datasource.name());
        }
        else
        {
            MultipleDataSource.setDataSource(DataSource.oracleDataSource);
        }
    }
}
註解方式實現切換數據源,搜索註釋,更換註釋上面的數據源,支持類註釋和方法註釋
public class MultipleDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<String> dataSources = new InheritableThreadLocal<String>();

    public static void setDataSource(String dataSource) {
        dataSources.set(dataSource);
    }

    //清除數據源
    public static void clearDataSource() {
        dataSources.remove();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return dataSources.get();
    }
}
繼承AbstractRoutingDataSource實現數據源切換
@DataSource(name = DataSource.mySqlDataSource)
public class ContentServiceImpl implements IContentService {

    @Autowired
    private IContentDao contentDao;

    @Override
    public Content queryOne(String type) {
        return contentDao.queryOne(type);
    }
}
使用demo

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在Global的 Application_BeginRequest方法中: Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN"); Thread.CurrentThread.CurrentUICulture = new Cult ...
  • public static class NumberToChinese { #region 數值轉為大寫(不帶圓角分) /// <summary> /// 數值轉為大寫(不帶圓角分) /// </summary> /// <param name="LowerMoney"></param> /// < ...
  • 最近燃料公司門戶做了一個待辦的彙總,從三個數據源拿數據彙總到首頁,這三個數據源分別是域認證的介面,域認證的webservices,證書加密的介面,下麵就這些介面,做一下簡單總結 1 pfx證書的探索過程 0.1 提供的代碼 1.1 pfx 百度百科對pfx的解釋是: 公鑰加密技術12號標準。 公鑰加 ...
  • 第6章 函數 ...
  • 1. 投票主頁面: 2.處理投票頁面: 3. 建立訪問資料庫的類,封裝用於引用: ...
  • 【題目描述】有個人的家族很大,輩分關係很混亂,請你幫整理一下這種關係。給出每個人的孩子的信息。輸入一個序列,使得每個人的後輩都比那個人後列出。 【輸入】第一行一個整數(1<=N<=100),表示家族的人數。接下來N行,第I行表示第I個人的兒子。每行最後是0表示描述完畢。 【輸出】輸出一個序列,使得每 ...
  • 1.重定向是什麼? 這裡說的重定向是由http協議規定的一種機制。其工作流程如下所述。 (1)客戶端發起http請求,訪問伺服器端組件。 (2)伺服器端返回一個狀態代碼為302的響應結果。該代碼的意思是讓瀏覽器再訪問另一個組件,響應結果中包含著訪問新組件的url地址。新的訪問組件可能在同一個應用中也 ...
  • 因為要在maven上搭建項目因此研究了一下,下麵來講講我搭建maven項目的過程。 一、下載maven 點擊進入http://maven.apache.org/download.cgi?Preferred=http%3A%2F%2Fmirror.bit.edu.cn%2Fapache%2F,點擊ap ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...