Microservices: Seata AT springCloud integrates distributed transactions in configuration mode (Part 2)

Table of contents

Previous: Install seata and start a successful portal

1 Introduction: 

2. The steps for springCloud to use seata at are as follows

The first step is to check the springCloud version

The second step is to add maven dependencies

The third step is to add yml configuration

Step 4: Configure the data source (druid) 

Step 5 fix a warning

 Step 6: Check the log for success after startup


Previous: Install seata and start a successful portal

Portal ===> Microservices: Seata AT distributed transactions and configuration methods (Part 1)

1 Introduction: 

-> Seata AT (Automatic Transaction) One of the distributed transaction solutions

It mainly solves the problem of transaction consistency in distributed systems. In a traditional distributed system, when multiple services need to perform transaction operations, each service needs to implement the management and coordination of distributed transactions by itself, which is prone to transaction inconsistencies. Seata AT uses the concept of global transaction and local transaction, and concentrates the management and coordination of transaction on Seata Server, realizing the consistency and reliability of distributed transaction. Specifically, Seata AT addresses the following issues:

  1. Distributed transaction coordination: Seata AT provides a global transaction manager responsible for coordinating and managing multiple local transactions to ensure the consistency of all branch transactions.

  2. Transaction isolation and atomicity: Seata AT guarantees that all branch transactions are successfully committed when the global transaction is committed, otherwise the global transaction is rolled back. This ensures transaction isolation and atomicity.

  3. Transaction recovery mechanism: Seata AT provides a transaction log storage service, which can restore the transaction failure state caused by network or other abnormalities, and improve the robustness of the system.

  4. Distributed lock mechanism: Seata AT uses a distributed lock mechanism to ensure that conflicts and data inconsistencies can be avoided when multiple transactions operate on the same resource at the same time.

 -> seata AT transaction concept:  

TC ((Transaction Coordinator)): The transaction coordinator
maintains the state of global and branch transactions, and drives global transaction commit or rollback.
TM (Transaction Manager): Transaction Manager
defines the scope of global transactions: start global transactions, commit or rollback global transactions.
RM (Resource Manager): Resource Manager
manages resources for branch transactions, talks to TC to register branch transactions and report the status of branch transactions, and drives branch transactions to commit or roll back.

2. The steps for springCloud to use seata at are as follows

The first step is to check the springCloud version

The second step is to add maven dependencies


         <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

The third step is to add yml configuration

#pzy 配置分布式事务 
seata:
  enabled: true # 1.0新特性,需要依赖seata-spring-boot-starter 默认为true
  enable-auto-data-source-proxy: true  # 牵扯到回滚
  tx-service-group: seata_group  # 需要与config.txt中的 service.vgroupMapping.seata_group=default保持一致
  server:
    vgroup-mapping:
      seata_group: default # 需要与config.txt中的 service.vgroupMapping.seata_group=default 保持一致
    #grouplist:
    #  default: 127.0.0.1:8091
    disable-global-transaction: false
  registry:  ## 注册中心
    type: nacos #注册nacos
    nacos:
      application: seata-server  #nacos中seata-server启动注册成功后的服务名称
      server-addr: *:8848
      username: *
      password: *
      group: SEATA_GROUP
      namespace: 49b38634-8a78-4216-a80c-7181976301c5
  config: ## 配置中心  与register.conf文件中的保持一致
    type: nacos
    nacos:
      server-addr: *:8848
      group: *#与register.conf文件中的保持一致
      username: *
      password: *
      namespace: 49b38634-8a78-4216-a80c-7181976301c5

Step 4: Configure the data source (druid) 

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import lombok.extern.slf4j.Slf4j;



import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;



import javax.sql.DataSource;

/**
 * 配置数据源,使用seata对数据源做代理
 */
@Slf4j
@Configuration
public class DataSourcesConfig {

// V1版本
//    @Value("${mybatis-plus.mapper-locations}")
//    private String mapperLocations;
//
//    @Bean
//    @ConfigurationProperties(prefix = "spring.datasource")
//    public DataSource druidDataSource() {
//        return new DruidDataSource();
//    }
//
//    /**
//     * 使用 io.seata.rm.datasource.DataSourceProxy
//     * @param druidDataSource
//     * @return
//     */
//    @Bean
//    public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
//        return new DataSourceProxy(druidDataSource);
//    }
//
//    @Bean
//    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
//        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//        bean.setDataSource(dataSourceProxy);
//        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        bean.setMapperLocations(resolver.getResources(mapperLocations));
//        return bean.getObject();
//    }

    //V2 版本
    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Bean(name = "dataSource") // 声明其为Bean实例
    @Primary // 在同样的DataSource中,首先使用被标注的DataSource
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        log.info("dataSourceProperties.getUrl():{}", dataSourceProperties.getUrl());
        druidDataSource.setUrl(dataSourceProperties.getUrl());
        druidDataSource.setUsername(dataSourceProperties.getUsername());
        druidDataSource.setPassword(dataSourceProperties.getPassword());
        druidDataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        druidDataSource.setInitialSize(0);
        druidDataSource.setMaxActive(180);
        druidDataSource.setMaxWait(60000);
        druidDataSource.setMinIdle(0);
        druidDataSource.setValidationQuery("Select 1 from DUAL");
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
        druidDataSource.setMinEvictableIdleTimeMillis(25200000);
        druidDataSource.setRemoveAbandoned(true);
        druidDataSource.setRemoveAbandonedTimeout(1800);
        druidDataSource.setLogAbandoned(true);
        log.info("装载dataSource........");
        return new DataSourceProxy(druidDataSource);
    }


}

[If mybatis plus pagination fails, some components fail, please use this set]

Step 5 fix a warning

Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be....

Undertow set the buffer pool, otherwise it will use the default, and a warning will appear when starting

import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

/**
 *
 *
 * 解决方案一: 配置文件
 * 解决方案二: application.properties的配置
 *
 * @author: pzy
 * @date: 2023-05-19
 * @description: 解决启动io.undertow.websockets.jsr UT026010: Buffer pool was not
 * set on WebSocketDeploymentInfo, the default pool will be used的警告
 */
@Component
public class CustomizationBean implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {

    @Override
    public void customize(UndertowServletWebServerFactory factory) {
        factory.addDeploymentInfoCustomizers(deploymentInfo -> {
            WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
            webSocketDeploymentInfo.setBuffers(
                    new DefaultByteBufferPool(false, 1024)
//                    new DefaultByteBufferPool(false, 1024,20,4)
            );
            deploymentInfo.addServletContextAttribute("io.undertow.websockets.jsr.WebSocketDeploymentInfo", webSocketDeploymentInfo);
        });
    }
}

 Step 6: Check the log for success after startup


examine: 

-> Check the undo_log database for undeleted data

-> Check the console for rm tm, commit rollback, etc. 

-> Write an error report in the remote service to see if the rollback is successful

Guess you like

Origin blog.csdn.net/pingzhuyan/article/details/130801805