找回密码
 立即注册
首页 业界区 业界 Seata源码—2.seata-samples项目介绍

Seata源码—2.seata-samples项目介绍

思矿戳 2025-6-2 23:37:53
大纲
1.seata-samples的配置文件和启动类
2.seata-samples业务服务启动时的核心工作
3.seata-samples库存服务的连接池配置
4.Seata对数据库连接池代理配置的分析
5.Dubbo RPC通信过程中传递全局事务XID
6.Seata跟Dubbo整合的Filter(基于SPI机制)
7.seata-samples的AT事务例子原理流程
8.Seata核心配置文件file.conf的内容介绍
 
1.seata-samples的配置文件和启动类
(1)seata-samples的测试步骤
(2)seata-samples用户服务的配置和启动类
(3)seata-samples库存服务的配置和启动类
(4)seata-samples订单服务的配置和启动类
(5)seata-samples业务服务的配置和启动类
 
示例仓库:
  1. https://github.com/seata/seata-samples
复制代码
示例代码的模块ID:seata-samples-dubbo
 
(1)seata-samples的测试步骤
步骤一:启动DubboAccountServiceStarter
步骤二:启动DubboStorageServiceStarter
步骤三:启动DubboOrderServiceStarter
步骤四:运行DubboBusinessTester
 
(2)seata-samples用户服务的配置和启动类
dubbo-account-service.xml配置文件:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.      xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
  5.      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">
  6.    
  7.    
  8.     <bean >
  9.         <property name="locations" value="classpath:jdbc.properties"/>
  10.     </bean>
  11.    
  12.    
  13.     <bean name="accountDataSource"  init-method="init" destroy-method="close">
  14.         <property name="url" value="${jdbc.account.url}"/>
  15.         <property name="username" value="${jdbc.account.username}"/>
  16.         <property name="password" value="${jdbc.account.password}"/>
  17.         <property name="driverClassName" value="${jdbc.account.driver}"/>
  18.         <property name="initialSize" value="0"/>
  19.         <property name="maxActive" value="180"/>
  20.         <property name="minIdle" value="0"/>
  21.         <property name="maxWait" value="60000"/>
  22.         <property name="validationQuery" value="Select 'x' from DUAL"/>
  23.         <property name="testOnBorrow" value="false"/>
  24.         <property name="testOnReturn" value="false"/>
  25.         <property name="testWhileIdle" value="true"/>
  26.         <property name="timeBetweenEvictionRunsMillis" value="60000"/>
  27.         <property name="minEvictableIdleTimeMillis" value="25200000"/>
  28.         <property name="removeAbandoned" value="true"/>
  29.         <property name="removeAbandonedTimeout" value="1800"/>
  30.         <property name="logAbandoned" value="true"/>
  31.         <property name="filters" value="mergeStat"/>
  32.     </bean>
  33.    
  34.    
  35.     <bean id="accountDataSourceProxy" >
  36.         <constructor-arg ref="accountDataSource"/>
  37.     </bean>
  38.    
  39.    
  40.     <bean id="jdbcTemplate" >
  41.         <property name="dataSource" ref="accountDataSourceProxy"/>
  42.     </bean>
  43.     <dubbo:application name="dubbo-demo-account-service">
  44.         <dubbo:parameter key="qos.enable" value="false"/>
  45.     </dubbo:application>
  46.     <dubbo:registry address="zookeeper://localhost:2181" />
  47.     <dubbo:protocol name="dubbo" port="20881"/>
  48.     <dubbo:service interface="io.seata.samples.dubbo.service.AccountService" ref="service" timeout="10000"/>
  49.    
  50.    
  51.     <bean id="service" >
  52.         <property name="jdbcTemplate" ref="jdbcTemplate"/>
  53.     </bean>
  54.    
  55.    
  56.     <bean >
  57.         <constructor-arg value="dubbo-demo-account-service"/>
  58.         <constructor-arg value="my_test_tx_group"/>
  59.     </bean>
  60. </beans>
复制代码
启动类:
  1. public class DubboAccountServiceStarter {
  2.     //Account service is ready. A buyer register an account: U100001 on my e-commerce platform
  3.     public static void main(String[] args) {
  4.         ClassPathXmlApplicationContext accountContext = new ClassPathXmlApplicationContext(
  5.             new String[] {"spring/dubbo-account-service.xml"}
  6.         );
  7.         accountContext.getBean("service");
  8.         JdbcTemplate accountJdbcTemplate = (JdbcTemplate)accountContext.getBean("jdbcTemplate");
  9.         accountJdbcTemplate.update("delete from account_tbl where user_id = 'U100001'");
  10.         accountJdbcTemplate.update("insert into account_tbl(user_id, money) values ('U100001', 999)");
  11.         new ApplicationKeeper(accountContext).keep();
  12.     }
  13. }
  14. //The type Application keeper.
  15. public class ApplicationKeeper {
  16.     private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationKeeper.class);
  17.     private final ReentrantLock LOCK = new ReentrantLock();
  18.     private final Condition STOP = LOCK.newCondition();
  19.     //Instantiates a new Application keeper.
  20.     public ApplicationKeeper(AbstractApplicationContext applicationContext) {
  21.         addShutdownHook(applicationContext);
  22.     }
  23.    
  24.     private void addShutdownHook(final AbstractApplicationContext applicationContext) {
  25.         Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
  26.             @Override
  27.             public void run() {
  28.                 try {
  29.                     applicationContext.close();
  30.                     LOGGER.info("ApplicationContext " + applicationContext + " is closed.");
  31.                 } catch (Exception e) {
  32.                     LOGGER.error("Failed to close ApplicationContext", e);
  33.                 }
  34.                 LOCK.lock();
  35.                 try {
  36.                     STOP.signal();
  37.                 } finally {
  38.                     LOCK.unlock();
  39.                 }
  40.             }
  41.         }));
  42.     }
  43.    
  44.     public void keep() {
  45.         LOCK.lock();
  46.         try {
  47.             LOGGER.info("Application is keep running ... ");
  48.             STOP.await();
  49.         } catch (InterruptedException e) {
  50.             LOGGER.error("ApplicationKeeper.keep() is interrupted by InterruptedException!", e);
  51.         } finally {
  52.             LOCK.unlock();
  53.         }
  54.     }
  55. }
复制代码
(3)seata-samples库存服务的配置和启动类
dubbo-stock-service.xml配置文件:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.      xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
  5.      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">
  6.    
  7.    
  8.     <bean >
  9.         <property name="locations" value="classpath:jdbc.properties"/>
  10.     </bean>
  11.    
  12.    
  13.     <bean name="stockDataSource"  init-method="init" destroy-method="close">
  14.         <property name="url" value="${jdbc.stock.url}"/>
  15.         <property name="username" value="${jdbc.stock.username}"/>
  16.         <property name="password" value="${jdbc.stock.password}"/>
  17.         <property name="driverClassName" value="${jdbc.stock.driver}"/>
  18.         <property name="initialSize" value="0"/>
  19.         <property name="maxActive" value="180"/>
  20.         <property name="minIdle" value="0"/>
  21.         <property name="maxWait" value="60000"/>
  22.         <property name="validationQuery" value="Select 'x' from DUAL"/>
  23.         <property name="testOnBorrow" value="false"/>
  24.         <property name="testOnReturn" value="false"/>
  25.         <property name="testWhileIdle" value="true"/>
  26.         <property name="timeBetweenEvictionRunsMillis" value="60000"/>
  27.         <property name="minEvictableIdleTimeMillis" value="25200000"/>
  28.         <property name="removeAbandoned" value="true"/>
  29.         <property name="removeAbandonedTimeout" value="1800"/>
  30.         <property name="logAbandoned" value="true"/>
  31.         <property name="filters" value="mergeStat"/>
  32.     </bean>
  33.    
  34.    
  35.     <bean id="stockDataSourceProxy" >
  36.         <constructor-arg ref="stockDataSource"/>
  37.     </bean>
  38.    
  39.     <bean id="jdbcTemplate" >
  40.         <property name="dataSource" ref="stockDataSourceProxy"/>
  41.     </bean>
  42.     <dubbo:application name="dubbo-demo-stock-service">
  43.         <dubbo:parameter key="qos.enable" value="false"/>
  44.     </dubbo:application>
  45.     <dubbo:registry address="zookeeper://localhost:2181" />
  46.     <dubbo:protocol name="dubbo" port="20882"/>
  47.     <dubbo:service interface="io.seata.samples.dubbo.service.StockService" ref="service" timeout="10000"/>
  48.    
  49.    
  50.     <bean id="service" >
  51.         <property name="jdbcTemplate" ref="jdbcTemplate"/>
  52.     </bean>
  53.    
  54.    
  55.     <bean >
  56.         <constructor-arg value="dubbo-demo-stock-service"/>
  57.         <constructor-arg value="my_test_tx_group"/>
  58.     </bean>
  59. </beans>
复制代码
启动类:
  1. //The type Dubbo stock service starter.
  2. public class DubboStockServiceStarter {
  3.     //Stock service is ready. A seller add 100 stock to a sku: C00321
  4.     public static void main(String[] args) {
  5.         ClassPathXmlApplicationContext stockContext = new ClassPathXmlApplicationContext(
  6.             new String[] {"spring/dubbo-stock-service.xml"}
  7.         );
  8.         stockContext.getBean("service");
  9.         JdbcTemplate stockJdbcTemplate = (JdbcTemplate)stockContext.getBean("jdbcTemplate");
  10.         stockJdbcTemplate.update("delete from stock_tbl where commodity_code = 'C00321'");
  11.         stockJdbcTemplate.update("insert into stock_tbl(commodity_code, count) values ('C00321', 100)");
  12.         new ApplicationKeeper(stockContext).keep();
  13.     }
  14. }
复制代码
(4)seata-samples订单服务的配置和启动类
dubbo-order-service.xml配置文件:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.      xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
  5.      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">
  6.    
  7.    
  8.     <bean >
  9.         <property name="locations" value="classpath:jdbc.properties"/>
  10.     </bean>
  11.    
  12.    
  13.     <bean name="accountDataSource"  init-method="init" destroy-method="close">
  14.         <property name="url" value="${jdbc.account.url}"/>
  15.         <property name="username" value="${jdbc.account.username}"/>
  16.         <property name="password" value="${jdbc.account.password}"/>
  17.         <property name="driverClassName" value="${jdbc.account.driver}"/>
  18.         <property name="initialSize" value="0"/>
  19.         <property name="maxActive" value="180"/>
  20.         <property name="minIdle" value="0"/>
  21.         <property name="maxWait" value="60000"/>
  22.         <property name="validationQuery" value="Select 'x' from DUAL"/>
  23.         <property name="testOnBorrow" value="false"/>
  24.         <property name="testOnReturn" value="false"/>
  25.         <property name="testWhileIdle" value="true"/>
  26.         <property name="timeBetweenEvictionRunsMillis" value="60000"/>
  27.         <property name="minEvictableIdleTimeMillis" value="25200000"/>
  28.         <property name="removeAbandoned" value="true"/>
  29.         <property name="removeAbandonedTimeout" value="1800"/>
  30.         <property name="logAbandoned" value="true"/>
  31.         <property name="filters" value="mergeStat"/>
  32.     </bean>
  33.    
  34.    
  35.     <bean id="accountDataSourceProxy" >
  36.         <constructor-arg ref="accountDataSource"/>
  37.     </bean>
  38.    
  39.    
  40.     <bean id="jdbcTemplate" >
  41.         <property name="dataSource" ref="accountDataSourceProxy"/>
  42.     </bean>
  43.     <dubbo:application name="dubbo-demo-account-service">
  44.         <dubbo:parameter key="qos.enable" value="false"/>
  45.     </dubbo:application>
  46.     <dubbo:registry address="zookeeper://localhost:2181" />
  47.     <dubbo:protocol name="dubbo" port="20881"/>
  48.     <dubbo:service interface="io.seata.samples.dubbo.service.AccountService" ref="service" timeout="10000"/>
  49.    
  50.    
  51.     <bean id="service" >
  52.         <property name="jdbcTemplate" ref="jdbcTemplate"/>
  53.     </bean>
  54.    
  55.    
  56.     <bean >
  57.         <constructor-arg value="dubbo-demo-account-service"/>
  58.         <constructor-arg value="my_test_tx_group"/>
  59.     </bean>
  60. </beans>            
复制代码
启动类:
  1. //The type Dubbo order service starter.
  2. public class DubboOrderServiceStarter {
  3.     //The entry point of application.
  4.     public static void main(String[] args) {
  5.         //Order service is ready . Waiting for buyers to order
  6.         ClassPathXmlApplicationContext orderContext = new ClassPathXmlApplicationContext(
  7.             new String[] {"spring/dubbo-order-service.xml"}
  8.         );
  9.         orderContext.getBean("service");
  10.         new ApplicationKeeper(orderContext).keep();
  11.     }
  12. }
复制代码
(5)seata-samples业务服务的配置和启动类
dubbo-business.xml配置文件:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.      xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
  5.      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">
  6.     <dubbo:application name="dubbo-demo-app">
  7.         <dubbo:parameter key="qos.enable" value="false"/>
  8.         <dubbo:parameter key="qos.accept.foreign.ip" value="false"/>
  9.         <dubbo:parameter key="qos.port" value="33333"/>
  10.     </dubbo:application>
  11.     <dubbo:registry address="zookeeper://localhost:2181" />
  12.     <dubbo:reference id="orderService" check="false" interface="io.seata.samples.dubbo.service.OrderService"/>
  13.     <dubbo:reference id="stockService" check="false" interface="io.seata.samples.dubbo.service.StockService"/>
  14.     <bean id="business" >
  15.         <property name="orderService" ref="orderService"/>
  16.         <property name="stockService" ref="stockService"/>
  17.     </bean>
  18.    
  19.    
  20.     <bean >
  21.         <constructor-arg value="dubbo-demo-app"/>
  22.         <constructor-arg value="my_test_tx_group"/>
  23.     </bean>
  24. </beans>
复制代码
启动类:
  1. //The type Dubbo business tester.
  2. public class DubboBusinessTester {
  3.     //The entry point of application.
  4.     public static void main(String[] args) {
  5.         //The whole e-commerce platform is ready, The buyer(U100001) create an order on the sku(C00321) , the count is 2
  6.         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
  7.             new String[] {"spring/dubbo-business.xml"}
  8.         );
  9.         //模拟调用下单接口
  10.         final BusinessService business = (BusinessService)context.getBean("business");
  11.         business.purchase("U100001", "C00321", 2);
  12.     }
  13. }
复制代码
 
2.seata-samples业务服务启动时的核心工作
BusinessService业务服务启动时,会创建两个服务接口的动态代理。一个是OrderService订单服务接口的Dubbo动态代理,另一个是StockService库存服务接口的Dubbo动态代理。BusinessService业务服务的下单接口会添加@GlobalTransaction注解,通过@GlobalTransaction注解开启一个分布式事务,Seata的内核组件GlobalTransactionScanner就会扫描到这个注解。
1.png
  1. //The type Dubbo business tester.
  2. public class DubboBusinessTester {
  3.     //The entry point of application.
  4.     public static void main(String[] args) {
  5.         //The whole e-commerce platform is ready , The buyer(U100001) create an order on the sku(C00321) , the count is 2
  6.         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
  7.             new String[] {"spring/dubbo-business.xml"}
  8.         );
  9.         //模拟调用下单接口
  10.         final BusinessService business = (BusinessService)context.getBean("business");
  11.         business.purchase("U100001", "C00321", 2);
  12.     }
  13. }
  14. public class BusinessServiceImpl implements BusinessService {
  15.     private static final Logger LOGGER = LoggerFactory.getLogger(BusinessService.class);
  16.     private StockService stockService;
  17.     private OrderService orderService;
  18.     private Random random = new Random();
  19.     @Override
  20.     @GlobalTransactional(timeoutMills = 300000, name = "dubbo-demo-tx")//分布式事务如果5分钟还没跑完,就是超时
  21.     public void purchase(String userId, String commodityCode, int orderCount) {
  22.         LOGGER.info("purchase begin ... xid: " + RootContext.getXID());
  23.         stockService.deduct(commodityCode, orderCount);
  24.         orderService.create(userId, commodityCode, orderCount);
  25.         if (random.nextBoolean()) {
  26.             throw new RuntimeException("random exception mock!");
  27.         }
  28.     }
  29.    
  30.     //Sets stock service.
  31.     public void setStockService(StockService stockService) {
  32.         this.stockService = stockService;
  33.     }
  34.    
  35.     //Sets order service.
  36.     public void setOrderService(OrderService orderService) {
  37.         this.orderService = orderService;
  38.     }
  39. }
复制代码
 
3.seata-samples库存服务的连接池配置
首先会把jdbc.properties文件里的配置加载进来,然后将配置配置的值注入到库存服务的数据库连接池,接着通过Seata的DataSourceProxy对数据库连接池进行代理。
 
一.启动类
  1. //The type Dubbo stock service starter.
  2. public class DubboStockServiceStarter {
  3.     //Stock service is ready. A seller add 100 stock to a sku: C00321
  4.     public static void main(String[] args) {
  5.         ClassPathXmlApplicationContext stockContext = new ClassPathXmlApplicationContext(
  6.             new String[] {"spring/dubbo-stock-service.xml"}
  7.         );
  8.         stockContext.getBean("service");
  9.         JdbcTemplate stockJdbcTemplate = (JdbcTemplate)stockContext.getBean("jdbcTemplate");
  10.         stockJdbcTemplate.update("delete from stock_tbl where commodity_code = 'C00321'");
  11.         stockJdbcTemplate.update("insert into stock_tbl(commodity_code, count) values ('C00321', 100)");
  12.         new ApplicationKeeper(stockContext).keep();
  13.     }
  14. }
复制代码
二.dubbo-stock-service.xml文件
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.      xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
  5.      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">
  6.    
  7.    
  8.     <bean >
  9.         <property name="locations" value="classpath:jdbc.properties"/>
  10.     </bean>
  11.    
  12.    
  13.     <bean name="accountDataSource"  init-method="init" destroy-method="close">
  14.         <property name="url" value="${jdbc.account.url}"/>
  15.         <property name="username" value="${jdbc.account.username}"/>
  16.         <property name="password" value="${jdbc.account.password}"/>
  17.         <property name="driverClassName" value="${jdbc.account.driver}"/>
  18.         <property name="initialSize" value="0"/>
  19.         <property name="maxActive" value="180"/>
  20.         <property name="minIdle" value="0"/>
  21.         <property name="maxWait" value="60000"/>
  22.         <property name="validationQuery" value="Select 'x' from DUAL"/>
  23.         <property name="testOnBorrow" value="false"/>
  24.         <property name="testOnReturn" value="false"/>
  25.         <property name="testWhileIdle" value="true"/>
  26.         <property name="timeBetweenEvictionRunsMillis" value="60000"/>
  27.         <property name="minEvictableIdleTimeMillis" value="25200000"/>
  28.         <property name="removeAbandoned" value="true"/>
  29.         <property name="removeAbandonedTimeout" value="1800"/>
  30.         <property name="logAbandoned" value="true"/>
  31.         <property name="filters" value="mergeStat"/>
  32.     </bean>
  33.    
  34.    
  35.     <bean id="accountDataSourceProxy" >
  36.         <constructor-arg ref="accountDataSource"/>
  37.     </bean>
  38.    
  39.    
  40.     <bean id="jdbcTemplate" >
  41.         <property name="dataSource" ref="accountDataSourceProxy"/>
  42.     </bean>
  43.     <dubbo:application name="dubbo-demo-account-service">
  44.         <dubbo:parameter key="qos.enable" value="false"/>
  45.     </dubbo:application>
  46.     <dubbo:registry address="zookeeper://localhost:2181" />
  47.     <dubbo:protocol name="dubbo" port="20881"/>
  48.     <dubbo:service interface="io.seata.samples.dubbo.service.AccountService" ref="service" timeout="10000"/>
  49.    
  50.    
  51.     <bean id="service" >
  52.         <property name="jdbcTemplate" ref="jdbcTemplate"/>
  53.     </bean>
  54.    
  55.    
  56.     <bean >
  57.         <constructor-arg value="dubbo-demo-account-service"/>
  58.         <constructor-arg value="my_test_tx_group"/>
  59.     </bean>
  60. </beans>
复制代码
三.jdbc.properties文件文件
  1. jdbc.account.url=jdbc:mysql://localhost:3306/seata
  2. jdbc.account.username=root
  3. jdbc.account.password=123456
  4. jdbc.account.driver=com.mysql.jdbc.Driver
  5. # stock db config
  6. jdbc.stock.url=jdbc:mysql://localhost:3306/seata
  7. jdbc.stock.username=root
  8. jdbc.stock.password=123456
  9. jdbc.stock.driver=com.mysql.jdbc.Driver
  10. # order db config
  11. jdbc.order.url=jdbc:mysql://localhost:3306/seata
  12. jdbc.order.username=root
  13. jdbc.order.password=123456
  14. jdbc.order.driver=com.mysql.jdbc.Driver
复制代码
 
4.Seata对数据库连接池代理配置的分析
数据库连接池代理DataSourceProxy,会注入到JdbcTemplate数据库操作组件中。这样库存或者订单服务就可以通过Spring数据库操作组件JdbcTemplate,向Seata数据库连接池代理DataSourceProxy获取一个数据库连接。然后通过数据库连接,把SQL请求发送给MySQL进行处理。
2.png
 
5.Dubbo RPC通信过程中传递全局事务XID
BusinessService对StockService进行RPC调用时,会传递全局事务XID。StockService便可以根据RootContext.getXID()获取到全局事务XID。
  1. public class BusinessServiceImpl implements BusinessService {
  2.     private static final Logger LOGGER = LoggerFactory.getLogger(BusinessService.class);
  3.     private StockService stockService;
  4.     private OrderService orderService;
  5.     private Random random = new Random();
  6.     @Override
  7.     @GlobalTransactional(timeoutMills = 300000, name = "dubbo-demo-tx")//分布式事务如果5分钟还没跑完,就是超时
  8.     public void purchase(String userId, String commodityCode, int orderCount) {
  9.         LOGGER.info("purchase begin ... xid: " + RootContext.getXID());
  10.         stockService.deduct(commodityCode, orderCount);
  11.         orderService.create(userId, commodityCode, orderCount);
  12.         if (random.nextBoolean()) {
  13.             throw new RuntimeException("random exception mock!");
  14.         }
  15.     }
  16.     ...
  17. }
  18. public class StockServiceImpl implements StockService {
  19.     private static final Logger LOGGER = LoggerFactory.getLogger(StockService.class);
  20.     private JdbcTemplate jdbcTemplate;
  21.     @Override
  22.     public void deduct(String commodityCode, int count) {
  23.         LOGGER.info("Stock Service Begin ... xid: " + RootContext.getXID());
  24.         LOGGER.info("Deducting inventory SQL: update stock_tbl set count = count - {} where commodity_code = {}", count, commodityCode);
  25.         jdbcTemplate.update("update stock_tbl set count = count - ? where commodity_code = ?", new Object[] {count, commodityCode});
  26.         LOGGER.info("Stock Service End ... ");
  27.     }
  28.     ...
  29. }
复制代码
3.png
 
6.Seata跟Dubbo整合的Filter(基于SPI机制)
Seata与Dubbo整合的Filter过滤器ApacheDubboTransactionPropagationFilter会将向SeataServer注册的全局事务xid,设置到RootContext中。
4.png
5.png
 
7.seata-samples的AT事务例子原理流程
6.png
 
8.Seata核心配置文件file.conf的内容介绍
  1. # Seata网络通信相关的配置
  2. transport {
  3.     # 网络通信的类型是TCP
  4.     type = "TCP"
  5.     # 网络服务端使用NIO模式
  6.     server = "NIO"
  7.     # 是否开启心跳
  8.     heartbeat = true
  9.     # 是否允许Seata的客户端批量发送请求
  10.     enableClientBatchSendRequest = true
  11.     # 使用Netty进行网络通信时的线程配置
  12.     threadFactory {
  13.         bossThreadPrefix = "NettyBoss"
  14.         workerThreadPrefix = "NettyServerNIOWorker"
  15.         serverExecutorThread-prefix = "NettyServerBizHandler"
  16.         shareBossWorker = false
  17.         clientSelectorThreadPrefix = "NettyClientSelector"
  18.         clientSelectorThreadSize = 1
  19.         clientWorkerThreadPrefix = "NettyClientWorkerThread"
  20.         # 用来监听和建立网络连接的Boss线程的数量
  21.         bossThreadSize = 1
  22.         # 默认的Worker线程数量是8
  23.         workerThreadSize = "default"
  24.     }
  25.     shutdown {
  26.         # 销毁服务端的时候的等待时间是多少秒
  27.         wait = 3
  28.     }
  29.     # 序列化类型是Seata
  30.     serialization = "seata"
  31.     # 是否开启压缩
  32.     compressor = "none"
  33. }
  34. # Seata服务端相关的配置
  35. service {
  36.     # 分布式事务的分组
  37.     vgroupMapping.my_test_tx_group = "default"
  38.     # only support when registry.type=file, please don't set multiple addresses
  39.     default.grouplist = "127.0.0.1:8091"
  40.     # 是否开启降级
  41.     enableDegrade = false
  42.     # 是否禁用全局事务
  43.     disableGlobalTransaction = false
  44. }
  45. # Seata客户端相关的配置
  46. client {
  47.     # 数据源管理组件的配置
  48.     rm {
  49.         # 异步提交缓冲区的大小
  50.         asyncCommitBufferLimit = 10000
  51.         # 锁相关的配置:重试间隔、重试次数、回滚冲突处理
  52.         lock {
  53.             retryInterval = 10
  54.             retryTimes = 30
  55.             retryPolicyBranchRollbackOnConflict = true
  56.         }
  57.         reportRetryCount = 5
  58.         tableMetaCheckEnable = false
  59.         reportSuccessEnable = false
  60.     }
  61.     # 事务管理组件的配置
  62.     tm {
  63.         commitRetryCount = 5
  64.         rollbackRetryCount = 5
  65.     }
  66.     # 回滚日志的配置
  67.     undo {
  68.         dataValidation = true
  69.         logSerialization = "jackson"
  70.         logTable = "undo_log"
  71.     }
  72.     # log日志的配置
  73.     log {
  74.         exceptionRate = 100
  75.     }
  76. }
复制代码
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册