sharding-jdbc源碼解析


參考博客:https://cloud.tencent.com/developer/article/1529692

 

 

 

 

 

 

 看sharding-jdbc支持XA協議重點看下面的代碼

 

 

 sharding-transaction-xa-atomikos模塊中主要是原生的atomikos的配置,atomikos事務配置都是在transactions.properties中進行配置的

sharding-transaction模塊由sharding-transaction-core,sharding-transaction-2pc和sharding-transaction-base這3個子模塊組成。

Apache ShardingSphere(Incubating)能夠自動將XADataSource作為數據庫驅動的數據源接入XA事務管理器。而針對於使用DataSource作為數據庫驅動的應用,用戶也無需改變其編碼以及配置,Apache ShardingSphere(Incubating)通過自動適配的方式,在中間件內部將其轉化為支持XA協議的XADataSource和XAConnection,並將其作為XA資源注冊到底層的XA事務管理器中。

ShardingSphere還會實現XA協議的recovery部分,即在事務處理器出現崩潰的情況時,可以有能力提供in-doubt transactions來實現事務恢復。

 

 

 

不支持informix數據庫atomikosTransactionManager

 

 

 

 

 

 sharding-jdbc支持事務上面的兩個注解是需要的

 @Transactional表示底層使用spring的事務管理,spring底層的事務管理器使用默認的com.atomikos.icatch.jta.UserTransactionManager

 

 

 

<?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">
 
 
    <!--==========針對兩個庫,各配置一個AtomikosDataSourceBean,底層都使用MysqlXADataSource=====================-->
    <!--配置數據源db_user-->
    <bean id="db_user" class="com.atomikos.jdbc.AtomikosDataSourceBean"
          init-method="init" destroy-method="close">
        <property name="uniqueResourceName" value="ds1" />
        <property name="xaDataSourceClassName"
                  value="com.mysql.cj.jdbc.MysqlXADataSource" />
        <property name="xaProperties">
            <props>
                <prop key="url">jdbc:mysql://localhost:3306/db_user?serverTimezone=UTC</prop>
                <prop key="user">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
 
    <!--配置數據源db_account-->
    <bean id="db_account" class="com.atomikos.jdbc.AtomikosDataSourceBean"
          init-method="init" destroy-method="close">
        <property name="uniqueResourceName" value="ds2" />
        <property name="xaDataSourceClassName"
                  value="com.mysql.cj.jdbc.MysqlXADataSource" />
        <property name="xaProperties">
            <props>
                <prop key="url">jdbc:mysql://localhost:3306/db_account?serverTimezone=UTC</prop>
                <prop key="user">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
 
    <!--=============針對兩個數據源,各配置一個SqlSessionFactoryBean============ -->
    <bean id="ssf_user" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="db_user" />
    </bean>
 
    <bean id="ssf_account" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="db_account" />
    </bean>
 
    <!--=============針對兩個SqlSessionFactoryBean,各配置一個MapperScannerConfigurer============ -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="ssf_user"/>
        <!--指定com.tianshouzhi.atomikos.mappers.db_user包下的UserMapper接口使用ssf_user獲取底層數據庫連接-->
        <property name="basePackage" value="com.tianshouzhi.atomikos.mappers.db_user"/>
    </bean>
 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="ssf_account"/>
        <!--指定com.tianshouzhi.atomikos.mappers.ds_account包下的AccountMapper接口使用ssf_account獲取底層數據庫連接-->
        <property name="basePackage" value="com.tianshouzhi.atomikos.mappers.ds_account"/>
    </bean>
 
    <!--================配置atomikos事務管理器========================-->
    <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init"
          destroy-method="close">
        <property name="forceShutdown" value="false"/>
    </bean>
 
    <!--============配置spring的JtaTransactionManager,底層委派給atomikos進行處理===============-->
    <bean id="jtaTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="transactionManager" ref="atomikosTransactionManager"/>
    </bean>
 
    <!--配置spring聲明式事務管理器-->
    <tx:annotation-driven transaction-manager="jtaTransactionManager"/>
 
    <bean id="jtaService" class="com.tianshouzhi.atomikos.JTAService"/>
</beans>

第二個注解 @ShardingTransactionType(TransactionType.XA)也是需要的,改注解sharding-jdbc將一般的數據源攔截成XADatasource,將一般的事務管理器封裝成XA的事務管理器atomikosTransactionManager

 

這里的原理在於

https://blog.csdn.net/liu1390910/article/details/94554356

 

 

 

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

com.atomikos.icatch.serial_jta_transactions = false
com.atomikos.icatch.default_jta_timeout = 300000
com.atomikos.icatch.max_actives = 10000
com.atomikos.icatch.checkpoint_interval = 50000
com.atomikos.icatch.enable_logging = true
com.atomikos.icatch.log_base_name = xa_tx
com.atomikos.icatch.log_base_dir = ./logs

atomikos 創建數據源,報Max number of active transactions

 
技術小美  2017-11-15 13:25:00 瀏覽1828
 
在使用atomikos 事務管理中,當並發數超過50的時候會產生異常如下:
java.lang.IllegalStateException:Max number of active transactions reched:50

原因:

atomikos的默認配置中 transactions.properties中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# SAMPLE PROPERTIES FILE FOR THE TRANSACTION SERVICE
# THIS FILE ILLUSTRATES THE DIFFERENT SETTINGS FOR THE TRANSACTION MANAGER
# UNCOMMENT THE ASSIGNMENTS TO OVERRIDE DEFAULT VALUES;
 
# Required: factory implementation  class  of the transaction core.
# NOTE: there is no  default  for  this , so it MUST be specified! 
com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory
 
         
# Set base name of file where messages are output 
# (also known as the  'console file' ).
#
# com.atomikos.icatch.console_file_name = tm.out
 
# Size limit (in bytes)  for  the console file;
# negative means unlimited.
#
# com.atomikos.icatch.console_file_limit=- 1
 
# For size-limited console files,  this  option
# specifies a number of rotating files to 
# maintain.
#
# com.atomikos.icatch.console_file_count= 1
 
# Set the number of log writes between checkpoints
#
# com.atomikos.icatch.checkpoint_interval= 500
 
# Set output directory where console file and other files are to be put
# make sure  this  directory exists!
#
# com.atomikos.icatch.output_dir = ./
 
# Set directory of log files; make sure  this  directory exists!
#
# com.atomikos.icatch.log_base_dir = ./
 
# Set base name of log file
this  name will be  used as the first part of 
# the system-generated log file name
#
# com.atomikos.icatch.log_base_name = tmlog
 
# Set the max number of active local transactions 
# or - 1  for  unlimited.
#
# com.atomikos.icatch.max_actives =  50  (原因)
 
# Set the  default  timeout (in milliseconds)  for  local transactions
#
# com.atomikos.icatch.default_jta_timeout =  10000
 
# Set the max timeout (in milliseconds)  for  local transactions
#
# com.atomikos.icatch.max_timeout =  300000
 
# The globally unique name of  this  transaction manager process
# override  this  value with a globally unique name
#
# com.atomikos.icatch.tm_unique_name = tm
     
# Do we want to use parallel subtransactions? JTA's  default
# is NO  for  J2EE compatibility
#
# com.atomikos.icatch.serial_jta_transactions= true
                     
# If you want to  do  explicit resource registration then
# you need to set  this  value to  false .
#
# com.atomikos.icatch.automatic_resource_registration= true  
     
# Set  this  to WARN, INFO or DEBUG to control the granularity
# of output to the console file.
#
# com.atomikos.icatch.console_log_level=WARN
     
# Do you want transaction logging to be enabled or not?
# If set to  false , then no logging overhead will be done
# at the risk of losing data after restart or crash.
#
# com.atomikos.icatch.enable_logging= true
 
# Should two-phase commit be done in (multi-)threaded mode or not?
# Set  this  to  false  if  you want commits to be ordered according
# to the order in which resources are added to the transaction.
#
# NOTE: threads are reused on JDK  1.5  or higher. 
# For JDK  1.4 , thread reuse is enabled as soon as the 
# concurrent backport is in the classpath - see 
# http: //mirrors.ibiblio.org/pub/mirrors/maven2/backport-util-concurrent/backport-util-concurrent/
#
# com.atomikos.icatch.threaded_2pc= false
 
# Should shutdown of the VM trigger shutdown of the transaction core too?
#
# com.atomikos.icatch.force_shutdown_on_vm_exit= false

修改默認配置中的:

 

1
com.atomikos.icatch.max_actives =  50 ------改為更大就可以解決
 
http://www.voidcn.com/article/p-odlbtmrm-boe.html

 使用atomikos時,事務默認超時時間是100000毫秒,超過這個時間,提交事務就會拋出異常com.atomikos.icatch.RollbackException: Prepare: NO vote。

    今天總算通過bing找到了答案,記錄一下。

    在網上很多說的要設置com.atomikos.icatch.max_timeout和com.atomikos.icatch.default_jta_timeout,居然都沒說怎么設置,集成Spring的情況下,第一時間想到在bean的屬性里配置,結果沒找到(default_jta_timeout可以在org.springframework.transaction.jta.JtaTransactionManager中找到defaultTimeOut屬性與之匹配,但是max_timeout沒有找到,官方文檔(https://www.atomikos.com/Documentation/JtaProperties)也沒說,只是說設置max_timeout和UserTransaction.setTransactionTimeout()是一個意思,結果我配置了半天,沒有效果)。最后搞明白了,需要在classpath下建一個jta.properties(或者transactions.properties)文件(事務管理器的配置),來配置事務相關屬性,如下是我的jta.properties。

    PS:default_jta_timeout表示開啟事務時,默認的超時時間,max_timeout表示最大的超時時間,0表示無限時間。如果default_jta_timeout設置的值超過了max_timeout,會自動將超時時間截斷,使用max_timeout的值(日志會打印出來)。

 

 然后,Spring的配置文件

<!-- Atomikos 事務管理器配置 -->
    <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
        init-method="init" destroy-method="close">
        <!-- <property name="startupTransactionService" value="false" /> -->
        <!-- close()時是否強制終止事務 -->
        <property name="forceShutdown" value="false" />
    </bean>

    <!-- Atomikos UserTransaction配置 -->
    <bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp"></bean>

    <!-- JTA事務管理器 -->
    <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="transactionManager">
            <ref bean="atomikosTransactionManager" />
        </property>
        <property name="userTransaction">
            <ref bean="atomikosUserTransaction" />
        </property>
    </bean>
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />

 為XA和非XA提供內置的JDBC適配器,所有不再需要配置多余的東西

 

 

 

 sharding-transaction-core主要的功能在於ShardingTransactionManager類以spi擴展的是是哪些事務類型來生成對於的事務管理器,例如當前是XA的atomitx事務管理器,那么這里ShardingTransactionManager對於的事務管理器就是com.atomikos.icatch.jta.UserTransactionManager

 

 

 

 sharding-transaction-spring模塊就是掃描斷言的,當你的方法配置了@ShardingTransactionType (TransactionType.XA)注解之后,harding-transaction-spring模塊會攔截到改注解,通過Threadlocal切換當前事務類型,適用於Sharding-JDBC。例如:TransactionTypeHolder.set (TransactionType.XA),代碼如下

 

 Apache ShardingSphere(Incubating)官方目前實現了基於Atomikos和Bitronix的SPI,並且邀請了Radhat JBoss的XA事務引擎Narayana [https://github.com/jbosstm/narayana] 開發團隊實現了JBoss的SPI。用戶可以自行的在Atomikos,Bitronix和Narayana間選擇自己喜歡的XA事務管理器。

 

 

 

 sharding-transaction-xa-sp模塊就是sharding-jdbc提供的模塊,將外部的XAresource資源封裝到事務管理器中XATransactionManager中,這里XA


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM