首页 > 其他分享 >Seata解决分布式事务

Seata解决分布式事务

时间:2023-08-31 12:44:04浏览次数:31  
标签:事务 seata name nacos server application 分布式 id Seata

简介

Seata 是阿里开源的一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。

初始化数据库

创建 seata 库,初始化脚本如下

-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
    `xid`                       VARCHAR(128) NOT NULL,
    `transaction_id`            BIGINT,
    `status`                    TINYINT      NOT NULL,
    `application_id`            VARCHAR(32),
    `transaction_service_group` VARCHAR(32),
    `transaction_name`          VARCHAR(128),
    `timeout`                   INT,
    `begin_time`                BIGINT,
    `application_data`          VARCHAR(2000),
    `gmt_create`                DATETIME,
    `gmt_modified`              DATETIME,
    PRIMARY KEY (`xid`),
    KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(96),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

使用docker安装

docker pull seataio/seata-server:1.5.0
docker run -d --name seata-server -p 8091:8091 -p 7091:7091 seataio/seata-server:1.5.0

修改配置文件

docker exec -it seata-server sh #不能使用 /bin/bash
docker cp seata-server:/seata-server/resources/application.yml .
docker cp seata-server:/seata-server/resources/application.example.yml .

默认的配置文件 application.yml 内容如下

server:
  port: 7091

spring:
  application:
    name: seata-server

logging:
  config: classpath:logback-spring.xml
  file:
    path: ${user.home}/logs/seata
  extend:
    logstash-appender:
      destination: 127.0.0.1:4560
    kafka-appender:
      bootstrap-servers: 127.0.0.1:9092
      topic: logback_to_logstash

console:
  user:
    username: seata
    password: seata

seata:
  config:
    # support: nacos, consul, apollo, zk, etcd3
    type: file
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: file
  store:
    # support: file 、 db 、 redis
    mode: file
#  server:
#    service-port: 8091 #If not configured, the default is '${server.port} + 1000'
  security:
    secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
    tokenValidityInMilliseconds: 1800000
    ignore:
      urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login# 

参考 application.example.yml,修改之后为

server:
  port: 7091

spring:
  application:
    name: seata-server

logging:
  config: classpath:logback-spring.xml
  file:
    path: ${user.home}/logs/seata
  extend:
    logstash-appender:
      destination: 127.0.0.1:4560
    kafka-appender:
      bootstrap-servers: 127.0.0.1:9092
      topic: logback_to_logstash

console:
  user:
    username: seata
    password: seata

seata:
  config:
    type: nacos
    nacos:
      server-addr: ip:8848
      namespace: d8b0df04-aa58-4a5b-b582-7d133b9e8b2c
      group: SEATA_GROUP
      username: nacos
      password: nacos
      data-id: seataServer.properties
  registry:
    type: nacos
    nacos:
      application: seata-server
      server-addr: ip:8848
      group: SEATA_GROUP
      namespace: d8b0df04-aa58-4a5b-b582-7d133b9e8b2c
      cluster: default
      username: nacos
      password: nacos
  store:
    mode: db
    db:
      datasource: druid
      db-type: mysql
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://ip:port/seata?rewriteBatchedStatements=true&serverTimezone=UTC
      user: root
      password: xxx
      min-conn: 5
      max-conn: 100
      global-table: global_table
      branch-table: branch_table
      lock-table: lock_table
      distributed-lock-table: distributed_lock
      query-limit: 100
      max-wait: 5000
  security:
    secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
    tokenValidityInMilliseconds: 1800000
    ignore:
      urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login# 

使用nacos当做配置中心和注册中心,使用数据库存储。配置MySQL8.0所需要的jar

wget https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.19/mysql-connector-java-8.0.19.jar
docker cp application.yml seata-server:/seata-server/resources/
docker cp mysql-connector-java-8.0.19.jar seata-server:/seata-server/libs/
docker restart seata-server

查看nacos服务列表,可以看到seata-server服务,说明启动成功。

SpringBoot多项目使用seata(HttpClient调用)

参与分布式的数据库要创建 undo_log 表

CREATE TABLE undo_log
(
    id            BIGINT(20)   NOT NULL AUTO_INCREMENT,
    branch_id     BIGINT(20)   NOT NULL,
    xid           VARCHAR(100) NOT NULL,
    context       VARCHAR(128) NOT NULL,
    rollback_info LONGBLOB     NOT NULL,
    log_status    INT(11)      NOT NULL,
    log_created   DATETIME     NOT NULL,
    log_modified  DATETIME     NOT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY ux_undo_log (xid, branch_id)
) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;

业务使用表如下

create table if not exists tb_order
(
    id         bigint auto_increment primary key comment '主键',
    product_id bigint comment '商品id',
    quantity   int comment '购买数量',
    price      decimal(10, 2) comment '总金额'
);

create table if not exists tb_product
(
    id    bigint auto_increment primary key comment '主键',
    name  varchar(20) comment '商品名称',
    stock int comment '库存量'
);

insert into tb_product(name, stock)
values ('小米手机', 100);

一个订单表,一个商品表,订单服务创建订单的过程中会调用商品服务来减库存,调用过程中会将全局事务id传递过去。

  1. 商品服务成功,订单成功,事务成功
  2. 商品服务失败,订单也失败,事务失败
  3. 商品服务成功,订单失败,事务回滚

项目代码

order 服务

配置 seata 地址

seata:
  application-id: ${spring.application.name} # Seata 应用编号,默认为 ${spring.application.name}
  tx-service-group: ${spring.application.name}-group # Seata 事务组编号,用于 TC 集群名
  # 服务配置项,对应 ServiceProperties 类
  service:
    # 虚拟组和分组的映射
    vgroup-mapping:
      spring-seata-order-group: default
    # 分组和 Seata 服务的映射
    grouplist:
      default: ip:8091
  enabled: false
spring:
  application:
    name: spring-seata-order
  datasource:
    url: jdbc:mysql://ip:port/testdb?characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
    username: root
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      max-lifetime: 30000
  cloud:
    nacos:
      discovery:
        namespace: d8b0df04-aa58-4a5b-b582-7d133b9e8b2c
        username: nacos
        password: nacos
        server-addr: ip:8848

服务调用,底层通过 nacos 做负载均衡

String resp = restTemplate.postForObject("http://spring-seata-product/api/v1/product/reduceProductStock", null, String.class);

通过拦截器,将 seata 的分布式事物 id 传递到其他服务,seata 内的 TransactionPropagationInterceptor 拦截器获取到此 id 并保存到 RootContext 中。

@Component
public class RestTemplateBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RestTemplate) {
            ((RestTemplate) bean).getInterceptors()
                    .add((request, body, execution) -> {
                        String xid = RootContext.getXID();
                        if (Objects.nonNull(xid)) {
                            request.getHeaders().add(RootContext.KEY_XID, xid);
                        }
                        return execution.execute(request, body);
                    });

        }
        return bean;
    }
}

product 服务

配置 seata 地址

seata:
  application-id: ${spring.application.name} # Seata 应用编号,默认为 ${spring.application.name}
  tx-service-group: ${spring.application.name}-group # Seata 事务组编号,用于 TC 集群名
  # 服务配置项,对应 ServiceProperties 类
  service:
    # 虚拟组和分组的映射
    vgroup-mapping:
      spring-seata-order-group: default
    # 分组和 Seata 服务的映射
    grouplist:
      default: ip:8091
  enabled: false
spring:
  application:
    name: spring-seata-product
  datasource:
    url: jdbc:mysql://ip:port/testdb?characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
    username: root
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      max-lifetime: 30000
  cloud:
    nacos:
      discovery:
        namespace: d8b0df04-aa58-4a5b-b582-7d133b9e8b2c
        username: nacos
        password: nacos
        server-addr: ip:8848

参考

Seata快速入门-官方文档
使用 Docker 部署 Seata Server (1.5.0)
芋道 Spring Boot 分布式事务 Seata 入门

标签:事务,seata,name,nacos,server,application,分布式,id,Seata
From: https://www.cnblogs.com/strongmore/p/17185763.html

相关文章

  • 分布式深度学习技术概述
    分布式深度学习技术有哪些?分布式深度学习技术是指将深度学习模型的训练过程分布在多个计算资源上进行加速的技术。这样可以充分利用集群中的多个GPU、CPU或者多台计算机,加快深度学习模型的训练过程,提高训练效率。以下是一些常见的分布式深度学习技术:数据并行:将训练数据划分成......
  • PyTorch多卡分布式训练DDP单机多卡
    前言因为课题组发的卡还没有下来,先向导师问了实验室的两张卡借用。之前都是单卡训练模型,正好在这个机会实践以下单机多卡训练模型的方法。关于DDP网上有很多资料,但都比较零碎(有些博客的代码甚至没办法run),Pytorch给出的官方文档看起来也比较吃力。因此这篇文章的主要目的是......
  • Springboot 如何使用事务来操作一些业务
    事务的介绍事务具有4个特性:原子性、一致性、隔离性、持久性。通常称为ACID特性。原子性(Atomicity): 一个事务是一个不可分割的工作单位,事务中包括的诸多操作要么都做,要么都不做。一致性(Consistency):事务必须使数据库从一个一致性状态变成另一个一致性状态隔离性(Isolation):一个事......
  • 分布式光伏储能系统远程监控运维解决方案
    行业背景随着经济发展对于能源需求的不断提升,光伏发电作为一种重要的可再生清洁能源,受到国家和企业的重点关注。光伏发电是将太阳能转换为电能的过程,其输出功率“靠天吃饭”,容易受到太阳辐射强度、温度等环境因素影响,具有波动性、间歇性、不稳定性等特性。多地开始要求分布式新能源......
  • redis分布式锁,setnx+lua脚本的java实现
    1前言在现在工作中,为保障服务的高可用,应对单点故障、负载量过大等单机部署带来的问题,生产环境常用多机部署。为解决多机房部署导致的数据不一致问题,我们常会选择用分布式锁。目前其他比较常见的实现方案我列举在下面:基于缓存实现分布式锁(本文主要使用redis实现)基于数据库实......
  • redis高级用法:慢查询、pipline与事务、发布订阅、bitmap位图、HyperLogLog、GEO地理位
    目录一高级用法之慢查询1.1生命周期1.2两个配置1.2.1slowlog-max-len1.2.2slowlog-max-len1.3设置慢查询1.5作用二pipline与事务2.1什么是pipeline(管道)2.2python客户端实现pipline2.3与原生操作对比2.4使用建议2.5原生redis操作操作事务三发布订阅3.1角色3.2模......
  • redis分布式锁,setnx+lua脚本的java实现 | 京东物流技术团队
    1前言在现在工作中,为保障服务的高可用,应对单点故障、负载量过大等单机部署带来的问题,生产环境常用多机部署。为解决多机房部署导致的数据不一致问题,我们常会选择用分布式锁。目前其他比较常见的实现方案我列举在下面:基于缓存实现分布式锁(本文主要使用redis实现)基于数据库实现分布......
  • HBase 分布式数据库
    我从来没见过我们单位的主库系统,无论是小机或者EMC。如果哪天在值班时,收到通知主库挂了,我会觉得是一个深藏在机房沉重铁门里的大家伙,冒了几缕青烟,紧接着监控上各种Web小图标就都红了....在5、6年前,我们就希望能用分布式存储和分布式数据库来替代集中存储,觉得分布式廉价,而且高可靠。......
  • Kafka - 不仅是消息引擎,还是分布式流处理平台
     如果你通读全篇文字但只能记住一句话,我希望你记住的就是这句ApacheKafka是消息引擎系统,也是一个分布式流处理平台(DistributedStreamingPlatform) 作为流处理平台,Kafka与其他主流大数据流式计算框架相比,优势在哪里呢?我能想到的有两点。第一点是更容易实现端到端的正......
  • Centos7 安装 seata1.7.0
    seata官网: https://seata.io/zh-cn/index.htmlseata下载地址:   https://github.com/seata/seata 1、下载seata包wgethttps://github.com/seata/seata/releases/download/v1.7.0/seata-server-1.7.0.tar.gz2、解压tarzxvfseata-server-1.7.0.tar.gz-C/......