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

大纲

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业务服务的配置和启动类

 

示例仓库:

https://github.com/seata/seata-samples

示例代码的模块ID:seata-samples-dubbo

 

(1)seata-samples的测试步骤

步骤一:启动DubboAccountServiceStarter

步骤二:启动DubboStorageServiceStarter

步骤三:启动DubboOrderServiceStarter

步骤四:运行DubboBusinessTester

 

(2)seata-samples用户服务的配置和启动类

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>
    
    <!-- 将配置文件里的值注入到库存服务的数据库连接池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>
    
    <!-- 创建数据库连接池代理,通过DataSourceProxy代理accountDataSourceProxy数据库连接池 -->
    <bean id="accountDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy">
        <constructor-arg ref="accountDataSource"/>
    </bean>
    
    <!-- 将数据库连接池代理accountDataSourceProxy注入到JdbcTemplate数据库操作组件中-->
    <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数据库操作组件注入到AccountServiceImpl中 -->
    <bean id="service" class="io.seata.samples.dubbo.service.impl.AccountServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    
    <!-- 全局事务注解扫描组件 -->
    <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库存服务的配置和启动类

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>
    
    <!-- 将配置文件里的值注入到库存服务的数据库连接池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>
    
    <!-- 创建数据库连接池代理,通过DataSourceProxy代理stockDataSource数据库连接池 -->
    <bean id="stockDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy">
        <constructor-arg ref="stockDataSource"/>
    </bean>

    <!-- 将数据库连接池代理stockDataSourceProxy注入到JdbcTemplate数据库操作组件中-->
    <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数据库操作组件注入到StockServiceImpl中 -->
    <bean id="service" class="io.seata.samples.dubbo.service.impl.StockServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    
    <!-- 全局事务注解扫描组件 -->
    <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订单服务的配置和启动类

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>
    
    <!-- 将配置文件里的值注入到库存服务的数据库连接池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>
    
    <!-- 创建数据库连接池代理,通过DataSourceProxy代理stockDataSource数据库连接池 -->
    <bean id="orderDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy">
        <constructor-arg ref="orderDataSource"/>
    </bean>
    
    <!-- 将数据库连接池代理orderDataSourceProxy注入到JdbcTemplate数据库操作组件中-->
    <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数据库操作组件注入到OrderServiceImpl中 -->
    <bean id="service" class="io.seata.samples.dubbo.service.impl.OrderServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
        <property name="accountService" ref="accountService"/>
    </bean>
    
    <!-- 全局事务注解扫描组件 -->
    <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业务服务的配置和启动类

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>
    
    <!-- 全局事务注解扫描组件 -->
    <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"}
        );
        //模拟调用下单接口
        final BusinessService business = (BusinessService)context.getBean("business");
        business.purchase("U100001", "C00321", 2);
    }
}

 

2.seata-samples业务服务启动时的核心工作

BusinessService业务服务启动时,会创建两个服务接口的动态代理。一个是OrderService订单服务接口的Dubbo动态代理,另一个是StockService库存服务接口的Dubbo动态代理。BusinessService业务服务的下单接口会添加@GlobalTransaction注解,通过@GlobalTransaction注解开启一个分布式事务,Seata的内核组件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"}
        );
        //模拟调用下单接口
        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")//分布式事务如果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库存服务的连接池配置

首先会把jdbc.properties文件里的配置加载进来,然后将配置配置的值注入到库存服务的数据库连接池,接着通过Seata的DataSourceProxy对数据库连接池进行代理。

 

一.启动类

//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>
    
    <!-- 将配置文件里的值注入到库存服务的数据库连接池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>
    
    <!-- 创建数据库连接池代理,通过DataSourceProxy代理stockDataSource数据库连接池 -->
    <bean id="stockDataSourceProxy" class="io.seata.rm.datasource.DataSourceProxy">
        <constructor-arg ref="stockDataSource"/>
    </bean>
    
    <!-- 将数据库连接池代理stockDataSourceProxy注入到JdbcTemplate数据库操作组件中-->
    <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数据库操作组件注入到StockServiceImpl中 -->
    <bean id="service" class="io.seata.samples.dubbo.service.impl.StockServiceImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    
    <!-- 全局事务注解扫描组件 -->
    <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对数据库连接池代理配置的分析

数据库连接池代理DataSourceProxy,会注入到JdbcTemplate数据库操作组件中。这样库存或者订单服务就可以通过Spring数据库操作组件JdbcTemplate,向Seata数据库连接池代理DataSourceProxy获取一个数据库连接。然后通过数据库连接,把SQL请求发送给MySQL进行处理。

 

5.Dubbo RPC通信过程中传递全局事务XID

BusinessService对StockService进行RPC调用时,会传递全局事务XID。StockService便可以根据RootContext.getXID()获取到全局事务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")//分布式事务如果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注册的全局事务xid,设置到RootContext中。

 

7.seata-samples的AT事务例子原理流程

 

8.Seata核心配置文件file.conf的内容介绍

# Seata网络通信相关的配置
transport {
    # 网络通信的类型是TCP
    type = "TCP"
    # 网络服务端使用NIO模式
    server = "NIO"
    # 是否开启心跳
    heartbeat = true
    # 是否允许Seata的客户端批量发送请求
    enableClientBatchSendRequest = true
    # 使用Netty进行网络通信时的线程配置
    threadFactory {
        bossThreadPrefix = "NettyBoss"
        workerThreadPrefix = "NettyServerNIOWorker"
        serverExecutorThread-prefix = "NettyServerBizHandler"
        shareBossWorker = false
        clientSelectorThreadPrefix = "NettyClientSelector"
        clientSelectorThreadSize = 1
        clientWorkerThreadPrefix = "NettyClientWorkerThread"
        # 用来监听和建立网络连接的Boss线程的数量
        bossThreadSize = 1
        # 默认的Worker线程数量是8
        workerThreadSize = "default"
    }
    shutdown {
        # 销毁服务端的时候的等待时间是多少秒
        wait = 3
    }
    # 序列化类型是Seata
    serialization = "seata"
    # 是否开启压缩
    compressor = "none"
}

# Seata服务端相关的配置
service {
    # 分布式事务的分组
    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
    # 是否禁用全局事务
    disableGlobalTransaction = false
}

# Seata客户端相关的配置
client {
    # 数据源管理组件的配置
    rm {
        # 异步提交缓冲区的大小
        asyncCommitBufferLimit = 10000
        # 锁相关的配置:重试间隔、重试次数、回滚冲突处理
        lock {
            retryInterval = 10
            retryTimes = 30
            retryPolicyBranchRollbackOnConflict = true
        }
        reportRetryCount = 5
        tableMetaCheckEnable = false
        reportSuccessEnable = false
    }
    # 事务管理组件的配置
    tm {
        commitRetryCount = 5
        rollbackRetryCount = 5
    }
    # 回滚日志的配置
    undo {
        dataValidation = true
        logSerialization = "jackson"
        logTable = "undo_log"
    }
    # log日志的配置
    log {
        exceptionRate = 100
    }
}

 

原创作者: mjunz 转载于: https://www.cnblogs.com/mjunz/p/18876811
基于开源大模型的教学实训智能体软件,帮助教师生成课前备课设计、课后检测问答,提升效率与效果,提供学生全时在线练习与指导,实现教学相长。 智能教学辅助系统 这是一个智能教学辅助系统的前端项目,基于 Vue3+TypeScript 开发,使用 Ant Design Vue 作为 UI 组件库。 功能模块 用户模块 登录/注册功能,支持学生和教师角色 毛玻璃效果的登录界面 教师模块 备课与设计:根据课程大纲自动设计教学内容 考核内容生成:自动生成多样化考核题目及参考答案 学情数据分析:自动化检测学生答案,提供数据分析 学生模块 在线学习助手:结合教学内容解答问题 实时练习评测助手:生成随练题目并纠错 管理模块 用户管理:管理员/教师/学生等用户基本管理 课件资源管理:按学科列表管理教师备课资源 大屏概览:使用统计、效率指数、学习效果等 技术栈 Vue3 TypeScript Pinia 状态管理 Ant Design Vue 组件库 Axios 请求库 ByteMD 编辑器 ECharts 图表库 Monaco 编辑器 双主题支持(专业科技风/暗黑风) 开发指南 # 安装依赖 npm install # 启动开发服务器 npm run dev # 构建生产版本 npm run build 简介 本项目旨在开发一个基于开源大模型的教学实训智能体软件,帮助教师生成课前备课设计、课后检测问答,提升效率与效果,提供学生全时在线练习与指导,实现教学相长。
<think>我们正在分析Seata RM客户端注册到事务服务器的日志。根据引用[2],分布式事务执行流程中,RM需要向TC汇报资源准备状态,这意味着RM必须成功注册到TC(事务协调器)才能参与分布式事务。引用[3]提到,在获取数据库连接时,Seata通过DataSourceProxy包装了原始连接,并在其中注册分支事务。因此,注册过程可能涉及连接建立和资源注册。 关键日志分析点: 1. RM启动时,是否成功连接到TC服务器(Seata Server)。 2. RM是否成功注册了自身的事务资源(如数据源)。 3. 注册过程中是否有异常。 通常,Seata的日志中会包含以下关键信息: - 尝试连接TC服务器的日志 - 连接成功或失败的日志 - 资源(如数据源)注册的日志 - 分支事务注册的日志 根据引用[1],我们需要确保客户端配置正确,特别是: - 事务分组(tx-service-group)配置必须与服务端的事务分组匹配。 - seata-server服务地址(default)配置正确。 引用[5]中提到了一些配置问题,比如在FeignClient中添加configuration属性,但这属于应用层配置,与RM注册到TC的底层连接关系不大。 常见问题: 1. 网络问题:RM无法连接到TC服务器,检查IP和端口。 2. 配置问题:事务分组不匹配。 3. 版本不兼容:客户端和服务端版本不一致。 日志分析示例(以常见日志为例): - 成功连接TC的日志:可能包含“register ... success”等字样。 - 连接失败:可能包含“connect failed”、“timeout”等字样。 - 资源注册:如“register resource success”或“register branch ...”。 如果日志中出现异常堆栈,需要根据异常类型进一步分析。 因此,在分析日志时,我们可以按照以下步骤: 1. 检查客户端启动日志中关于Seata初始化的部分。 2. 查找与TC连接相关的日志(如Netty连接)。 3. 查找资源注册(如DataSourceProxy)的日志。 4. 如果遇到错误,查看错误堆栈。 注意:Seata客户端日志级别通常设置为INFO,如果需要更详细的信息,可以调整为DEBUG。 下面是一个模拟的日志分析过程: 假设日志片段: ``` 2023-10-08 14:18:20.123 INFO [main] io.seata.common.loader.EnhancedServiceLoader - load ContextCore[null] extension by class[io.seata.core.context.ThreadLocalContextCore] 2023-10-08 14:18:20.456 INFO [main] io.seata.core.rpc.netty.NettyPoolableFactory - NettyPoolableFactory create channel to transactionRole:TMROLE,address:localhost:8091,msg:< RegisterTMRequest{applicationId='order-service', transactionServiceGroup='seata_transaction'} > 2023-10-08 14:18:20.789 INFO [main] io.seata.core.rpc.netty.RmNettyRemotingClient - register to RM resourceId:jdbc:mysql://127.0.0.1:3306/seata_order 2023-10-08 14:18:20.790 INFO [main] io.seata.core.rpc.netty.RmNettyRemotingClient - register RM success. channel:[id: 0x4a5c6f7e, L:/127.0.0.1:1234 - R:localhost/127.0.0.1:8091], version:1.5.1 ``` 上述日志显示: 1. 成功建立了到TC(localhost:8091)的连接。 2. 注册了RM资源(资源ID为jdbc:mysql://...)。 3. 注册成功。 如果出现错误,日志可能如下: ``` 2023-10-08 14:18:20.456 ERROR [main] io.seata.core.rpc.netty.NettyPoolableFactory - connect to localhost:8091 failed java.net.ConnectException: Connection refused: no further information ``` 这表示无法连接到TC,需要检查TC服务是否启动,网络是否畅通。 另外,事务分组不匹配的日志可能如下: ``` 2023-10-08 14:18:20.456 WARN [main] io.seata.core.rpc.netty.AbstractNettyRemotingClient - no available service 'seata_transaction' found, please make sure registry config correct ``` 这表示客户端配置的事务分组(seata_transaction)在TC端没有找到对应的集群,需要检查服务端和客户端的事务分组配置。 总结: 1. 确保Seata服务端已启动,并且客户端配置的服务地址正确(包括端口)。 2. 确保事务分组(tx-service-group)配置在客户端和服务端一致。 3. 检查日志中是否有错误堆栈,根据错误信息进一步排查。 如果问题仍然存在,可以尝试增加Seata客户端的日志级别(如DEBUG)来获取更详细的信息。 相关问题: 1. 如何配置Seata客户端的事务分组? 2. Seata服务端启动后,如何验证其可用性? 3. Seata客户端注册失败时,常见的排查步骤有哪些?</think>### Seata RM 客户端注册日志分析 在 Seata 中,RM(Resource Manager)客户端注册到事务服务器(TC)是分布式事务正常工作的基础。以下是关键日志分析点及常见问题排查: #### **1. 成功注册日志特征** - **连接建立**:客户端尝试连接 TC 服务器地址(如 `localhost:8091`) ```log INFO io.seata.core.rpc.netty.NettyPoolableFactory - NettyPool created for address: localhost:8091 ``` - **资源注册**:RM 向 TC 注册数据源代理资源 ```log INFO io.seata.core.rpc.netty.RmNettyRemotingClient - register RM resource: jdbc:mysql://127.0.0.1:3306/seata_db ``` - **分组匹配**:事务分组(如 `seata_transaction`)与服务端一致 ```log INFO io.seata.core.rpc.netty.AbstractNettyRemotingClient - register success, server version:1.5.1, channel:[id:0x7a1c8f9f] ``` #### **2. 常见失败日志与原因** - **连接拒绝**:TC 服务未启动或网络不通 ```log ERROR io.seata.core.rpc.netty.NettyPoolableFactory - connect to localhost:8091 failed java.net.ConnectException: Connection refused ``` - **分组不匹配**:客户端与服务端事务分组不一致 ```log WARN io.seata.core.rpc.netty.AbstractNettyRemotingClient - no available service 'seata_transaction' found ``` - **资源注册失败**:数据源未正确代理 ```log ERROR io.seata.rm.datasource.DataSourceProxy - register resource error: jdbc:mysql://127.0.0.1:3306/db ``` #### **3. 关键配置验证点** 1. **事务分组一致性**(引用[1]) 客户端配置必须与服务端一致: ```yaml seata: tx-service-group: seata_transaction # 分组名称需匹配 service: vgroup-mapping: seata_transaction: default # 映射到集群 ``` 2. **TC 地址正确性**(引用[1]) ```yaml seata: service: grouplist: default: localhost:8091 # 确认IP/端口可达 ``` 3. **数据源代理**(引用[3]) 需通过 `DataSourceProxy` 包装原始连接: ```java // 正确代理示例 @Bean public DataSource dataSource(DataSource druidDataSource) { return new DataSourceProxy(druidDataSource); // 关键代理 } ``` #### **4. 排查步骤** 1. **检查 TC 服务状态** 在 TC 服务器查看日志,确认端口监听: ```log INFO io.seata.core.rpc.netty.NettyServerBootstrap - Server started, listen port: 8091 ``` 2. **验证分组映射** 客户端启动时日志应显示分组映射: ```log INFO io.seata.core.rpc.netty.TmNettyRemotingClient - TM register client success:seata_transaction ``` 3. **确认 RM 资源注册** 成功时会有资源 ID 上报: ```log INFO io.seata.rm.RMClient - register resource: jdbc:mysql://127.0.0.1:3306/order_db ``` 4. **开启 DEBUG 日志** 在 `application.yml` 中添加: ```yaml logging: level: io.seata: DEBUG ``` > **典型问题案例**:若出现 `register RM failed` 但连接正常,需检查 Seata 客户端/服务端版本兼容性(如 1.5.x 与 1.4.x 协议不兼容)。 --- ### 相关问题 1. **如何解决 Seata 客户端连接 TC 超时问题?** 2. **事务分组 `tx-service-group` 的作用是什么?**(引用[1]) 3. **RM 注册失败时如何获取更详细的错误信息?** 4. **Seata 中 `DataSourceProxy` 的工作原理是什么?**(引用[3]) 5. **分布式事务二阶段提交时 RM 未收到 TC 通知,可能是什么原因?**(引用[2]) [^1]: 事务分组与服务地址配置 [^2]: 分布式事务执行流程 [^3]: 数据源代理与资源注册
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值