Seata源碼—2.seata-samples項目介紹
大綱
1.seata-samples的配置文件和啟動類
2.seata-samples業(yè)務(wù)服務(wù)啟動時的核心工作
3.seata-samples庫存服務(wù)的連接池配置
4.Seata對數(shù)據(jù)庫連接池代理配置的分析
5.Dubbo RPC通信過程中傳遞全局事務(wù)XID
6.Seata跟Dubbo整合的Filter(基于SPI機制)
7.seata-samples的AT事務(wù)例子原理流程
8.Seata核心配置文件file.conf的內(nèi)容介紹
1.seata-samples的配置文件和啟動類
(1)seata-samples的測試步驟
(2)seata-samples用戶服務(wù)的配置和啟動類
(3)seata-samples庫存服務(wù)的配置和啟動類
(4)seata-samples訂單服務(wù)的配置和啟動類
(5)seata-samples業(yè)務(wù)服務(wù)的配置和啟動類
示例倉庫:
https://github.com/seata/seata-samples
示例代碼的模塊ID:seata-samples-dubbo
(1)seata-samples的測試步驟
步驟一:啟動DubboAccountServiceStarter
步驟二:啟動DubboStorageServiceStarter
步驟三:啟動DubboOrderServiceStarter
步驟四:運行DubboBusinessTester
(2)seata-samples用戶服務(wù)的配置和啟動類
dubbo-account-service.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:dubbo="http://dubbo.apache.org/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd"> <!-- 把jdbc.properties文件里的配置加載進來 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:jdbc.properties"/> </bean> <!-- 將配置文件里的值注入到庫存服務(wù)的數(shù)據(jù)庫連接池accountDataSource中 --> <bean name="accountDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.account.url}"/> <property name="username" value="${jdbc.account.username}"/> <property name="password" value="${jdbc.account.password}"/> <property name="driverClassName" value="${jdbc.account.driver}"/> <property name="initialSize" value="0"/> <property name="maxActive" value="180"/> <property name="minIdle" value="0"/> <property name="maxWait" value="60000"/> <property name="validationQuery" value="Select 'x' from DUAL"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="25200000"/> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="1800"/> <property name="logAbandoned" value="true"/> <property name="filters" value="mergeStat"/> </bean> <!-- 創(chuàng)建數(shù)據(jù)庫連接池代理,通過DataSourceProxy代理accountDataSourceProxy數(shù)據(jù)庫連接池 --> <bean id="accountDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy"> <constructor-arg ref="accountDataSource"/> </bean> <!-- 將數(shù)據(jù)庫連接池代理accountDataSourceProxy注入到JdbcTemplate數(shù)據(jù)庫操作組件中--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="accountDataSourceProxy"/> </bean> <dubbo:application name="dubbo-demo-account-service"> <dubbo:parameter key="qos.enable" value="false"/> </dubbo:application> <dubbo:registry address="zookeeper://localhost:2181" /> <dubbo:protocol name="dubbo" port="20881"/> <dubbo:service interface="io.seata.samples.dubbo.service.AccountService" ref="service" timeout="10000"/> <!-- 將JdbcTemplate數(shù)據(jù)庫操作組件注入到AccountServiceImpl中 --> <bean id="service" class="io.seata.samples.dubbo.service.impl.AccountServiceImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> <!-- 全局事務(wù)注解掃描組件 --> <bean class="io.seata.spring.annotation.GlobalTransactionScanner"> <constructor-arg value="dubbo-demo-account-service"/> <constructor-arg value="my_test_tx_group"/> </bean> </beans>
啟動類:
public class DubboAccountServiceStarter { //Account service is ready. A buyer register an account: U100001 on my e-commerce platform public static void main(String[] args) { ClassPathXmlApplicationContext accountContext = new ClassPathXmlApplicationContext( new String[] {"spring/dubbo-account-service.xml"} ); accountContext.getBean("service"); JdbcTemplate accountJdbcTemplate = (JdbcTemplate)accountContext.getBean("jdbcTemplate"); accountJdbcTemplate.update("delete from account_tbl where user_id = 'U100001'"); accountJdbcTemplate.update("insert into account_tbl(user_id, money) values ('U100001', 999)"); new ApplicationKeeper(accountContext).keep(); } } //The type Application keeper. public class ApplicationKeeper { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationKeeper.class); private final ReentrantLock LOCK = new ReentrantLock(); private final Condition STOP = LOCK.newCondition(); //Instantiates a new Application keeper. public ApplicationKeeper(AbstractApplicationContext applicationContext) { addShutdownHook(applicationContext); } private void addShutdownHook(final AbstractApplicationContext applicationContext) { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { try { applicationContext.close(); LOGGER.info("ApplicationContext " + applicationContext + " is closed."); } catch (Exception e) { LOGGER.error("Failed to close ApplicationContext", e); } LOCK.lock(); try { STOP.signal(); } finally { LOCK.unlock(); } } })); } public void keep() { LOCK.lock(); try { LOGGER.info("Application is keep running ... "); STOP.await(); } catch (InterruptedException e) { LOGGER.error("ApplicationKeeper.keep() is interrupted by InterruptedException!", e); } finally { LOCK.unlock(); } } }
(3)seata-samples庫存服務(wù)的配置和啟動類
dubbo-stock-service.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:dubbo="http://dubbo.apache.org/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd"> <!-- 把jdbc.properties文件里的配置加載進來 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:jdbc.properties"/> </bean> <!-- 將配置文件里的值注入到庫存服務(wù)的數(shù)據(jù)庫連接池stockDataSource中 --> <bean name="stockDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.stock.url}"/> <property name="username" value="${jdbc.stock.username}"/> <property name="password" value="${jdbc.stock.password}"/> <property name="driverClassName" value="${jdbc.stock.driver}"/> <property name="initialSize" value="0"/> <property name="maxActive" value="180"/> <property name="minIdle" value="0"/> <property name="maxWait" value="60000"/> <property name="validationQuery" value="Select 'x' from DUAL"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="25200000"/> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="1800"/> <property name="logAbandoned" value="true"/> <property name="filters" value="mergeStat"/> </bean> <!-- 創(chuàng)建數(shù)據(jù)庫連接池代理,通過DataSourceProxy代理stockDataSource數(shù)據(jù)庫連接池 --> <bean id="stockDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy"> <constructor-arg ref="stockDataSource"/> </bean> <!-- 將數(shù)據(jù)庫連接池代理stockDataSourceProxy注入到JdbcTemplate數(shù)據(jù)庫操作組件中--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="stockDataSourceProxy"/> </bean> <dubbo:application name="dubbo-demo-stock-service"> <dubbo:parameter key="qos.enable" value="false"/> </dubbo:application> <dubbo:registry address="zookeeper://localhost:2181" /> <dubbo:protocol name="dubbo" port="20882"/> <dubbo:service interface="io.seata.samples.dubbo.service.StockService" ref="service" timeout="10000"/> <!-- 將JdbcTemplate數(shù)據(jù)庫操作組件注入到StockServiceImpl中 --> <bean id="service" class="io.seata.samples.dubbo.service.impl.StockServiceImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> <!-- 全局事務(wù)注解掃描組件 --> <bean class="io.seata.spring.annotation.GlobalTransactionScanner"> <constructor-arg value="dubbo-demo-stock-service"/> <constructor-arg value="my_test_tx_group"/> </bean> </beans>
啟動類:
//The type Dubbo stock service starter. public class DubboStockServiceStarter { //Stock service is ready. A seller add 100 stock to a sku: C00321 public static void main(String[] args) { ClassPathXmlApplicationContext stockContext = new ClassPathXmlApplicationContext( new String[] {"spring/dubbo-stock-service.xml"} ); stockContext.getBean("service"); JdbcTemplate stockJdbcTemplate = (JdbcTemplate)stockContext.getBean("jdbcTemplate"); stockJdbcTemplate.update("delete from stock_tbl where commodity_code = 'C00321'"); stockJdbcTemplate.update("insert into stock_tbl(commodity_code, count) values ('C00321', 100)"); new ApplicationKeeper(stockContext).keep(); } }
(4)seata-samples訂單服務(wù)的配置和啟動類
dubbo-order-service.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:dubbo="http://dubbo.apache.org/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd"> <!-- 把jdbc.properties文件里的配置加載進來 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:jdbc.properties"/> </bean> <!-- 將配置文件里的值注入到庫存服務(wù)的數(shù)據(jù)庫連接池orderDataSource中 --> <bean name="orderDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.order.url}"/> <property name="username" value="${jdbc.order.username}"/> <property name="password" value="${jdbc.order.password}"/> <property name="driverClassName" value="${jdbc.order.driver}"/> <property name="initialSize" value="0"/> <property name="maxActive" value="180"/> <property name="minIdle" value="0"/> <property name="maxWait" value="60000"/> <property name="validationQuery" value="Select 'x' from DUAL"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="25200000"/> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="1800"/> <property name="logAbandoned" value="true"/> <property name="filters" value="mergeStat"/> </bean> <!-- 創(chuàng)建數(shù)據(jù)庫連接池代理,通過DataSourceProxy代理stockDataSource數(shù)據(jù)庫連接池 --> <bean id="orderDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy"> <constructor-arg ref="orderDataSource"/> </bean> <!-- 將數(shù)據(jù)庫連接池代理orderDataSourceProxy注入到JdbcTemplate數(shù)據(jù)庫操作組件中--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="orderDataSourceProxy"/> </bean> <dubbo:application name="dubbo-demo-order-service"> <dubbo:parameter key="qos.enable" value="false"/> </dubbo:application> <dubbo:registry address="zookeeper://localhost:2181" /> <dubbo:protocol name="dubbo" port="20883"/> <dubbo:service interface="io.seata.samples.dubbo.service.OrderService" ref="service" timeout="10000"/> <dubbo:reference id="accountService" check="false" interface="io.seata.samples.dubbo.service.AccountService"/> <!-- 將JdbcTemplate數(shù)據(jù)庫操作組件注入到OrderServiceImpl中 --> <bean id="service" class="io.seata.samples.dubbo.service.impl.OrderServiceImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> <property name="accountService" ref="accountService"/> </bean> <!-- 全局事務(wù)注解掃描組件 --> <bean class="io.seata.spring.annotation.GlobalTransactionScanner"> <constructor-arg value="dubbo-demo-order-service"/> <constructor-arg value="my_test_tx_group"/> </bean> </beans>
啟動類:
//The type Dubbo order service starter. public class DubboOrderServiceStarter { //The entry point of application. public static void main(String[] args) { //Order service is ready . Waiting for buyers to order ClassPathXmlApplicationContext orderContext = new ClassPathXmlApplicationContext( new String[] {"spring/dubbo-order-service.xml"} ); orderContext.getBean("service"); new ApplicationKeeper(orderContext).keep(); } }
(5)seata-samples業(yè)務(wù)服務(wù)的配置和啟動類
dubbo-business.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:dubbo="http://dubbo.apache.org/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd"> <dubbo:application name="dubbo-demo-app"> <dubbo:parameter key="qos.enable" value="false"/> <dubbo:parameter key="qos.accept.foreign.ip" value="false"/> <dubbo:parameter key="qos.port" value="33333"/> </dubbo:application> <dubbo:registry address="zookeeper://localhost:2181" /> <dubbo:reference id="orderService" check="false" interface="io.seata.samples.dubbo.service.OrderService"/> <dubbo:reference id="stockService" check="false" interface="io.seata.samples.dubbo.service.StockService"/> <bean id="business" class="io.seata.samples.dubbo.service.impl.BusinessServiceImpl"> <property name="orderService" ref="orderService"/> <property name="stockService" ref="stockService"/> </bean> <!-- 全局事務(wù)注解掃描組件 --> <bean class="io.seata.spring.annotation.GlobalTransactionScanner"> <constructor-arg value="dubbo-demo-app"/> <constructor-arg value="my_test_tx_group"/> </bean> </beans>
啟動類:
//The type Dubbo business tester. public class DubboBusinessTester { //The entry point of application. public static void main(String[] args) { //The whole e-commerce platform is ready, The buyer(U100001) create an order on the sku(C00321) , the count is 2 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"spring/dubbo-business.xml"} ); //模擬調(diào)用下單接口 final BusinessService business = (BusinessService)context.getBean("business"); business.purchase("U100001", "C00321", 2); } }
2.seata-samples業(yè)務(wù)服務(wù)啟動時的核心工作
BusinessService業(yè)務(wù)服務(wù)啟動時,會創(chuàng)建兩個服務(wù)接口的動態(tài)代理。一個是OrderService訂單服務(wù)接口的Dubbo動態(tài)代理,另一個是StockService庫存服務(wù)接口的Dubbo動態(tài)代理。BusinessService業(yè)務(wù)服務(wù)的下單接口會添加@GlobalTransaction注解,通過@GlobalTransaction注解開啟一個分布式事務(wù),Seata的內(nèi)核組件GlobalTransactionScanner就會掃描到這個注解。
//The type Dubbo business tester. public class DubboBusinessTester { //The entry point of application. public static void main(String[] args) { //The whole e-commerce platform is ready , The buyer(U100001) create an order on the sku(C00321) , the count is 2 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"spring/dubbo-business.xml"} ); //模擬調(diào)用下單接口 final BusinessService business = (BusinessService)context.getBean("business"); business.purchase("U100001", "C00321", 2); } } public class BusinessServiceImpl implements BusinessService { private static final Logger LOGGER = LoggerFactory.getLogger(BusinessService.class); private StockService stockService; private OrderService orderService; private Random random = new Random(); @Override @GlobalTransactional(timeoutMills = 300000, name = "dubbo-demo-tx")//分布式事務(wù)如果5分鐘還沒跑完,就是超時 public void purchase(String userId, String commodityCode, int orderCount) { LOGGER.info("purchase begin ... xid: " + RootContext.getXID()); stockService.deduct(commodityCode, orderCount); orderService.create(userId, commodityCode, orderCount); if (random.nextBoolean()) { throw new RuntimeException("random exception mock!"); } } //Sets stock service. public void setStockService(StockService stockService) { this.stockService = stockService; } //Sets order service. public void setOrderService(OrderService orderService) { this.orderService = orderService; } }
3.seata-samples庫存服務(wù)的連接池配置
首先會把jdbc.properties文件里的配置加載進來,然后將配置配置的值注入到庫存服務(wù)的數(shù)據(jù)庫連接池,接著通過Seata的DataSourceProxy對數(shù)據(jù)庫連接池進行代理。
一.啟動類
//The type Dubbo stock service starter. public class DubboStockServiceStarter { //Stock service is ready. A seller add 100 stock to a sku: C00321 public static void main(String[] args) { ClassPathXmlApplicationContext stockContext = new ClassPathXmlApplicationContext( new String[] {"spring/dubbo-stock-service.xml"} ); stockContext.getBean("service"); JdbcTemplate stockJdbcTemplate = (JdbcTemplate)stockContext.getBean("jdbcTemplate"); stockJdbcTemplate.update("delete from stock_tbl where commodity_code = 'C00321'"); stockJdbcTemplate.update("insert into stock_tbl(commodity_code, count) values ('C00321', 100)"); new ApplicationKeeper(stockContext).keep(); } }
二.dubbo-stock-service.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:dubbo="http://dubbo.apache.org/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd"> <!-- 把jdbc.properties文件里的配置加載進來 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:jdbc.properties"/> </bean> <!-- 將配置文件里的值注入到庫存服務(wù)的數(shù)據(jù)庫連接池stockDataSource中 --> <bean name="stockDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.stock.url}"/> <property name="username" value="${jdbc.stock.username}"/> <property name="password" value="${jdbc.stock.password}"/> <property name="driverClassName" value="${jdbc.stock.driver}"/> <property name="initialSize" value="0"/> <property name="maxActive" value="180"/> <property name="minIdle" value="0"/> <property name="maxWait" value="60000"/> <property name="validationQuery" value="Select 'x' from DUAL"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <property name="minEvictableIdleTimeMillis" value="25200000"/> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="1800"/> <property name="logAbandoned" value="true"/> <property name="filters" value="mergeStat"/> </bean> <!-- 創(chuàng)建數(shù)據(jù)庫連接池代理,通過DataSourceProxy代理stockDataSource數(shù)據(jù)庫連接池 --> <bean id="stockDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy"> <constructor-arg ref="stockDataSource"/> </bean> <!-- 將數(shù)據(jù)庫連接池代理stockDataSourceProxy注入到JdbcTemplate數(shù)據(jù)庫操作組件中--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="stockDataSourceProxy"/> </bean> <dubbo:application name="dubbo-demo-stock-service"> <dubbo:parameter key="qos.enable" value="false"/> </dubbo:application> <dubbo:registry address="zookeeper://localhost:2181" /> <dubbo:protocol name="dubbo" port="20882"/> <dubbo:service interface="io.seata.samples.dubbo.service.StockService" ref="service" timeout="10000"/> <!-- 將JdbcTemplate數(shù)據(jù)庫操作組件注入到StockServiceImpl中 --> <bean id="service" class="io.seata.samples.dubbo.service.impl.StockServiceImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> <!-- 全局事務(wù)注解掃描組件 --> <bean class="io.seata.spring.annotation.GlobalTransactionScanner"> <constructor-arg value="dubbo-demo-stock-service"/> <constructor-arg value="my_test_tx_group"/> </bean> </beans>
三.jdbc.properties文件文件
jdbc.account.url=jdbc:mysql://localhost:3306/seata jdbc.account.username=root jdbc.account.password=123456 jdbc.account.driver=com.mysql.jdbc.Driver # stock db config jdbc.stock.url=jdbc:mysql://localhost:3306/seata jdbc.stock.username=root jdbc.stock.password=123456 jdbc.stock.driver=com.mysql.jdbc.Driver # order db config jdbc.order.url=jdbc:mysql://localhost:3306/seata jdbc.order.username=root jdbc.order.password=123456 jdbc.order.driver=com.mysql.jdbc.Driver
4.Seata對數(shù)據(jù)庫連接池代理配置的分析
數(shù)據(jù)庫連接池代理DataSourceProxy,會注入到JdbcTemplate數(shù)據(jù)庫操作組件中。這樣庫存或者訂單服務(wù)就可以通過Spring數(shù)據(jù)庫操作組件JdbcTemplate,向Seata數(shù)據(jù)庫連接池代理DataSourceProxy獲取一個數(shù)據(jù)庫連接。然后通過數(shù)據(jù)庫連接,把SQL請求發(fā)送給MySQL進行處理。
5.Dubbo RPC通信過程中傳遞全局事務(wù)XID
BusinessService對StockService進行RPC調(diào)用時,會傳遞全局事務(wù)XID。StockService便可以根據(jù)RootContext.getXID()獲取到全局事務(wù)XID。
public class BusinessServiceImpl implements BusinessService { private static final Logger LOGGER = LoggerFactory.getLogger(BusinessService.class); private StockService stockService; private OrderService orderService; private Random random = new Random(); @Override @GlobalTransactional(timeoutMills = 300000, name = "dubbo-demo-tx")//分布式事務(wù)如果5分鐘還沒跑完,就是超時 public void purchase(String userId, String commodityCode, int orderCount) { LOGGER.info("purchase begin ... xid: " + RootContext.getXID()); stockService.deduct(commodityCode, orderCount); orderService.create(userId, commodityCode, orderCount); if (random.nextBoolean()) { throw new RuntimeException("random exception mock!"); } } ... } public class StockServiceImpl implements StockService { private static final Logger LOGGER = LoggerFactory.getLogger(StockService.class); private JdbcTemplate jdbcTemplate; @Override public void deduct(String commodityCode, int count) { LOGGER.info("Stock Service Begin ... xid: " + RootContext.getXID()); LOGGER.info("Deducting inventory SQL: update stock_tbl set count = count - {} where commodity_code = {}", count, commodityCode); jdbcTemplate.update("update stock_tbl set count = count - ? where commodity_code = ?", new Object[] {count, commodityCode}); LOGGER.info("Stock Service End ... "); } ... }
6.Seata跟Dubbo整合的Filter(基于SPI機制)
Seata與Dubbo整合的Filter過濾器ApacheDubboTransactionPropagationFilter會將向SeataServer注冊的全局事務(wù)xid,設(shè)置到RootContext中。
7.seata-samples的AT事務(wù)例子原理流程
8.Seata核心配置文件file.conf的內(nèi)容介紹
# Seata網(wǎng)絡(luò)通信相關(guān)的配置 transport { # 網(wǎng)絡(luò)通信的類型是TCP type = "TCP" # 網(wǎng)絡(luò)服務(wù)端使用NIO模式 server = "NIO" # 是否開啟心跳 heartbeat = true # 是否允許Seata的客戶端批量發(fā)送請求 enableClientBatchSendRequest = true # 使用Netty進行網(wǎng)絡(luò)通信時的線程配置 threadFactory { bossThreadPrefix = "NettyBoss" workerThreadPrefix = "NettyServerNIOWorker" serverExecutorThread-prefix = "NettyServerBizHandler" shareBossWorker = false clientSelectorThreadPrefix = "NettyClientSelector" clientSelectorThreadSize = 1 clientWorkerThreadPrefix = "NettyClientWorkerThread" # 用來監(jiān)聽和建立網(wǎng)絡(luò)連接的Boss線程的數(shù)量 bossThreadSize = 1 # 默認的Worker線程數(shù)量是8 workerThreadSize = "default" } shutdown { # 銷毀服務(wù)端的時候的等待時間是多少秒 wait = 3 } # 序列化類型是Seata serialization = "seata" # 是否開啟壓縮 compressor = "none" } # Seata服務(wù)端相關(guān)的配置 service { # 分布式事務(wù)的分組 vgroupMapping.my_test_tx_group = "default" # only support when registry.type=file, please don't set multiple addresses default.grouplist = "127.0.0.1:8091" # 是否開啟降級 enableDegrade = false # 是否禁用全局事務(wù) disableGlobalTransaction = false } # Seata客戶端相關(guān)的配置 client { # 數(shù)據(jù)源管理組件的配置 rm { # 異步提交緩沖區(qū)的大小 asyncCommitBufferLimit = 10000 # 鎖相關(guān)的配置:重試間隔、重試次數(shù)、回滾沖突處理 lock { retryInterval = 10 retryTimes = 30 retryPolicyBranchRollbackOnConflict = true } reportRetryCount = 5 tableMetaCheckEnable = false reportSuccessEnable = false } # 事務(wù)管理組件的配置 tm { commitRetryCount = 5 rollbackRetryCount = 5 } # 回滾日志的配置 undo { dataValidation = true logSerialization = "jackson" logTable = "undo_log" } # log日志的配置 log { exceptionRate = 100 } }
詳細介紹后端技術(shù)棧的基礎(chǔ)內(nèi)容,包括但不限于:MySQL原理和優(yōu)化、Redis原理和應(yīng)用、JVM和G1原理和優(yōu)化、RocketMQ原理應(yīng)用及源碼、Kafka原理應(yīng)用及源碼、ElasticSearch原理應(yīng)用及源碼、JUC源碼、Netty源碼、zk源碼、Dubbo源碼、Spring源碼、Spring Boot源碼、SCA源碼、分布式鎖源碼、分布式事務(wù)、分庫分表和TiDB、大型商品系統(tǒng)、大型訂單系統(tǒng)等