Spring集成Seata

这篇具有很好参考价值的文章主要介绍了Spring集成Seata。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Seata的集成方式有:

1. Seata-All

2. Seata-Spring-Boot-Starter

3. Spring-Cloud-Starter-Seata

本案例使用Seata-All演示:

第一步:下载Seata

第二步:为了更好看到效果,我们将Seata的数据存储改为db

将seata\script\server\db\mysql.sql语句在mysql中执行,创建相关表

Spring集成Seata,spring,seata

 Spring集成Seata,spring,seata

 然后修改seata配置文件,相关配置可以参考application.example.yml,此处修改mode为db并且配置db相关配置

Spring集成Seata,spring,seata

启动seata:

Spring集成Seata,spring,seata

 第三步:开始集成Seata

1.在我们的项目pom.xml引入seata包(1.5.x有bug,我们使用1.4.2)

<!--seata-->
<dependency>
	<groupId>io.seata</groupId>
	<artifactId>seata-all</artifactId> 
</dependency>
<dependency>
    <groupId>com.esotericsoftware</groupId>
    <artifactId>kryo</artifactId>
</dependency>
<dependency>
    <groupId>de.javakaffee</groupId>
    <artifactId>kryo-serializers</artifactId>
</dependency>

2.application.properties

#环境配置
spring.profiles.active=dev

spring.application.name=user-service-provider
dubbo.application.id=user-service
dubbo.application.name=user-service


#dubbo.protocol.port=-1
#dubbo.protocol.name=dubbo

#多协议支持
dubbo.protocols.tri.name=tri
dubbo.protocols.tri.port=-1
dubbo.protocols.tri.id=tri

dubbo.protocols.dubbo.name=dubbo
dubbo.protocols.dubbo.port=-1
dubbo.protocols.dubbo.id=dubbo
#序列化方式
dubbo.protocols.dubbo.serialization=kryo

dubbo.application.logger=log4j
#调用信息跟踪-log4j 日志
#dubbo.protocol.accesslog=true
#调用信息跟踪-将访问日志输出到指定文件
#dubbo.protocol.accesslog=/log/access.log


#是否简化 url
#dubbo.registry.simplified=true
#dubbo.registry.id=zk-registry
#dubbo.registry.address=zookeeper://192.168.1.105:2181?timeout=20000
#dubbo.config-center.address=zookeeper://192.168.1.105:2181?timeout=20000
#dubbo.metadata-report.address=zookeeper://192.168.1.105:2181?timeout=20000
#多注册中心
#dubbo.registries.zk-registry.id=zk-registry
#dubbo.registries.zk-registry.address=zookeeper://192.168.1.105:2181?timeout=20000&blockUntilConnectedWait=30
dubbo.registries.nacos-registry.id=nacos-registry
dubbo.registries.nacos-registry.address=nacos://192.168.1.105:8848
#dubbo.registries.nacos-registry.address=nacos://192.168.1.105:8848?namespace=2e73933a-34d4-4fba-b21e-f08cd9b8adc9
dubbo.registry.use-as-config-center=false
dubbo.registry.use-as-metadata-center=false

#nacos配置中心
nacos.config.server-addr=192.168.1.105:8848

#mybatis
mybatis.mapper-locations= classpath*:com/lee/demo/dubbo/demo/dao/*Mapper.xml
mybatis.type-aliases-package=com.lee.demo.dubbo.demo.entity

#datasource
spring.datasource.url=jdbc:mysql://localhost:3308/coupon-platform?useUnicode=true&characterEncoding=utf8&useOldAliasMetadataBehavior=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=Aa1225102411
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

3.在resources目录下添加配置文件file.conf和registry.conf,seata会扫描这两个配置文件从而获取相关配置。

Spring集成Seata,spring,seata

registry.conf:

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "file"
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "file"
  file {
    name = "file.conf"
  }
}

file.conf:

transport {
  # tcp, unix-domain-socket
  type = "TCP"
  #NIO, NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the tm client batch send request enable
  enableTmClientBatchSendRequest = false
  # the rm client batch send request enable
  enableRmClientBatchSendRequest = true
   # the rm client rpc request timeout
  rpcRmRequestTimeout = 2000
  # the tm client rpc request timeout
  rpcTmRequestTimeout = 10000
  # the tc client rpc request timeout
  rpcTcRequestTimeout = 5000
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  #transaction service group mapping
  vgroupMapping.demo-tx-default-group = "default"
  #only support when registry.type=file, please don't set multiple addresses
  default.grouplist = "192.168.8.133:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}

client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    tableMetaCheckerInterval = 60000
    reportSuccessEnable = false
    sagaBranchRegisterEnable = false
    sagaJsonParser = "fastjson"
    sagaRetryPersistModeUpdate = false
    sagaCompensatePersistModeUpdate = false
    tccActionInterceptorOrder = -2147482648 #Ordered.HIGHEST_PRECEDENCE + 1000
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
    defaultGlobalTransactionTimeout = 60000
    degradeCheck = false
    degradeCheckPeriod = 2000
    degradeCheckAllowTimes = 10
    interceptorOrder = -2147482648 #Ordered.HIGHEST_PRECEDENCE + 1000
  }
  undo {
    dataValidation = true
    onlyCareUpdateColumns = true
    logSerialization = "kryo"
    logTable = "undo_log"
    compress {
      enable = true
      # allow zip, gzip, deflater, 7z, lz4, bzip2, zstd default is zip
      type = zip
      # if rollback info size > threshold, then will be compress
      # allow k m g t
      threshold = 64k
    }
  }
  loadBalance {
      type = "RandomLoadBalance"
      virtualNodes = 10
  }
}
log {
  exceptionRate = 100
}
tcc {
  fence {
    # tcc fence log table name
    logTableName = tcc_fence_log
    # tcc fence log clean period
    cleanPeriod = 1h
  }
}

4.编写Seata全局事务扫描器配置类SeataTransctionConfig:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.seata.spring.annotation.GlobalTransactionScanner;

@Configuration
public class SeataTransctionConfig {

	@Bean
	public GlobalTransactionScanner globalTransactionScanner() {
		String txServiceGroup = "demo-tx-default-group";
		return new GlobalTransactionScanner(txServiceGroup);
	}

}

注意:在file.conf中的service配置要和SeataTransctionConfig 中指定的txServiceGroup 一致

Spring集成Seata,spring,seata

5. 由于AT模型是使用本地undo_log进行回滚,因此,我们每个事务所在的数据库中需要添加该表

在seata github中有样板,链接:https://github.com/seata/seata/tree/develop/srcipt/client/at/db

Spring集成Seata,spring,seata

其中mysql.sql如下: 

-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log`  (
  `branch_id` bigint NOT NULL COMMENT 'branch transaction id',
  `xid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'global transaction id',
  `context` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'undo_log context,such as serialization',
  `rollback_info` longblob NOT NULL COMMENT 'rollback info',
  `log_status` int NOT NULL COMMENT '0:normal status,1:defense status',
  `log_created` datetime(6) NOT NULL COMMENT 'create datetime',
  `log_modified` datetime(6) NOT NULL COMMENT 'modify datetime',
  UNIQUE INDEX `ux_undo_log`(`xid`, `branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'AT transaction mode undo table' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of undo_log
-- ----------------------------

 Spring集成Seata,spring,seata

 测试:

Spring集成Seata,spring,seata

Spring集成Seata,spring,seata

在抛异常之前打断点,查看数据是否成功插入过:

看到记录插入成功,并且undo_log中记录了这两个事务的日志:

Spring集成Seata,spring,seata

断点继续往下走,触发异常,,已插入的数据被回滚,且undo_log被清空,分布式事务回滚正常。

Spring集成Seata,spring,seata

 

至此,Spring集成Seata演示完毕文章来源地址https://www.toymoban.com/news/detail-628678.html

到了这里,关于Spring集成Seata的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Spring Cloud】Spring Cloud Alibaba-- 分布式事务Seata原理

    Seata 是一款开源的分布式事务解决方案,致力于提供高性能与简单易用的分布式事务服务,为用户提供了 AT、TCC、SAGA 和 XA 几种不同的事务模式: AT模式:无侵入式的分布式事务解决方案,适合不希望对业务进行改造的场景,但由于需要添加全局事务锁,对影响高并发系统的

    2024年02月08日
    浏览(65)
  • Spring Cloud 系列:Seata 中TCC模式具体实现

    https://seata.io/zh-cn/docs/dev/mode/tcc-mode https://seata.io/zh-cn/docs/user/mode/tcc TCC模式与AT模式非常相似,每阶段都是独立事务,不同的是TCC通过人工编码来实现数据恢复。需要实现三个方法: Try:资源的检测和预留; Confirm:完成资源操作业务;要求 Try 成功 Confirm 一定要能成功。 Can

    2024年01月23日
    浏览(23)
  • Spring Cloud Alibaba全家桶(九)——分布式事务组件Seata

    本文小新为大家带来 分布式事务组件Seata 相关知识,具体内容包括 分布式事务简介 (包括: 事务简介 , 本地事务 , 分布式事务典型场景 , 分布式事务理论基础 , 分布式事务解决方案 ), 分布式事务Seata使用 (包括: Seata是什么 , Seata的三大角色 , Seata的设计思路

    2024年02月03日
    浏览(51)
  • 【Spring Cloud Alibaba Seata 处理分布式事务】——每天一点小知识

                                                                                   💧 S p r i n g C l o u d A l i b a b a S e a t a 处理分布式事务 color{#FF1493}{Spring Cloud Alibaba Seata 处理分布式事务} Sp r in g Cl o u d A l ibaba S e a t a 处理分布式事务 💧

    2024年02月12日
    浏览(34)
  • Seata TCC 模式下解决幂等、悬挂、空回滚问题 | Spring Cloud56

    通过以下系列章节: docker-compose 实现Seata Server高可用部署 | Spring Cloud 51 Seata AT 模式理论学习、事务隔离及部分源码解析 | Spring Cloud 52 Spring Boot集成Seata利用AT模式分布式事务示例 | Spring Cloud 53 Seata XA 模式理论学习、使用及注意事项 | Spring Cloud54 Seata TCC 模式理论学习、生产级

    2024年02月09日
    浏览(25)
  • 【Seata】微服务集成seata

    Seata是 2019 年 1 月份蚂蚁金服和阿里巴巴共同 开源的分布式事务解决方案。 官网http://seata.io/ Seata事务管理有三个角色: TC (Transaction Coordinator) - 事务协调者 : 维护全局和分支事务的状态 ,协调全局事务提交或回滚。 TM (Transaction Manager) - 事务管理器 : 定义全局事务的范围

    2024年02月16日
    浏览(33)
  • Spring | 基于SpringBoot的多数据源实战 - 使用seata实现多数据源的全局事务管理

    在软件开发中, 多数据源 的应用越来越普遍,特别是在 微服务架构 和 业务模块化 的场景下。多数据源能够让不同的业务模块和微服务拥有各自独立的数据存储,大大提高了系统的灵活性和可维护性。本文将深入探讨多数据源的配置和实施,以及在 Spring Boot 环境下,如何通

    2024年02月07日
    浏览(51)
  • 【合集】Spring Cloud 组件——架构进化史话 & Eureka,Nacos,OpenFeign,Ribbon,Sentinel,Gateway ,Seata+事务. . .

    Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁,领导选举,分布式会话,集群状态)。 注意: 首先,尽管Spring Cloud带有“Cloud”这个单词,但它并不是云计算解

    2024年02月08日
    浏览(31)
  • 【合集】Spring Cloud 组件——架构进化史话 & Eureka,Nacos,Apollo,OpenFeign,Ribbon,Sentinel,Gateway ,Seata+事务. . .

    Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁,领导选举,分布式会话,集群状态)。 注意: 首先,尽管Spring Cloud带有“Cloud”这个单词,但它并不是云计算解

    2024年02月03日
    浏览(72)
  • springboot dubbo seata nacos集成 分布式事务seata实现

    官网:http://seata.io/zh-cn/docs/overview/what-is-seata.html Seata 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。 官网;https://cn.dubbo.apache.org/zh-cn/overview/what/

    2024年02月13日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包