github: https://github.com/dtm-labs/dtm

本人使用场景, 目前微服务中存在的用户服务, 商品服务,订单服务, 支付服务, 在进行下单操作的时候,需要创建订单并扣减库存, 这个时候就需要保证事务的一致性, 但是对于目前的微服务架构来说就需要一套分布式的事务来实现,于是引入DTM

介绍:

  他是一种跨语言的分布式事务管理器,无论你是php,python,golang还是java,nodejs等,都可以使用它来解决

使用场景:

使用:

1)本地运行dtm

git clone https://github.com/dtm-labs/dtm && cd dtm
go run main.go
注:他是无需配置也可以运行起来,但是如果有定制需求的话, 可以将根目录下的conf.sample.yml文件改为conf.yml 启动的时候指定配置文件即可 go run .\main.go -c ./conf.yml

注: 在启动服务之前, 需要先执行sqls目录下的对应的存储引擎的相关sql,否则启动的时候会一直报表不存在的错误, 例如使用的是mysql, 则需要执行

CREATE DATABASE if not exists dtm_busi
/*!40100 DEFAULT CHARACTER SET utf8mb4 */
;
drop table if exists dtm_busi.user_account;
create table if not exists dtm_busi.user_account(
id int(11) PRIMARY KEY AUTO_INCREMENT,
user_id int(11) UNIQUE,
balance DECIMAL(10, 2) not null default '0',
trading_balance DECIMAL(10, 2) not null default '0',
create_time datetime DEFAULT now(),
update_time datetime DEFAULT now(),
key(create_time),
key(update_time)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
insert into dtm_busi.user_account (user_id, balance)
values (1, 10000),
(2, 10000) on DUPLICATE KEY
UPDATE balance =
values (balance); --------------------------------- create database if not exists dtm_barrier
/*!40100 DEFAULT CHARACTER SET utf8mb4 */
;
drop table if exists dtm_barrier.barrier;
create table if not exists dtm_barrier.barrier(
id bigint(22) PRIMARY KEY AUTO_INCREMENT,
trans_type varchar(45) default '',
gid varchar(128) default '',
branch_id varchar(128) default '',
op varchar(45) default '',
barrier_id varchar(45) default '',
reason varchar(45) default '' comment 'the branch type who insert this record',
create_time datetime DEFAULT now(),
update_time datetime DEFAULT now(),
key(create_time),
key(update_time),
UNIQUE key(gid, branch_id, op, barrier_id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4; ------------------------------------- CREATE DATABASE IF NOT EXISTS dtm
/*!40100 DEFAULT CHARACTER SET utf8mb4 */
;
drop table IF EXISTS dtm.trans_global;
CREATE TABLE if not EXISTS dtm.trans_global (
`id` bigint(22) NOT NULL AUTO_INCREMENT,
`gid` varchar(128) NOT NULL COMMENT 'global transaction id',
`trans_type` varchar(45) not null COMMENT 'transaction type: saga | xa | tcc | msg',
`status` varchar(12) NOT NULL COMMENT 'transaction status: prepared | submitted | aborting | succeed | failed',
`query_prepared` varchar(1024) NOT NULL COMMENT 'url to check for msg|workflow',
`protocol` varchar(45) not null comment 'protocol: http | grpc | json-rpc',
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`finish_time` datetime DEFAULT NULL,
`rollback_time` datetime DEFAULT NULL,
`options` varchar(1024) DEFAULT '' COMMENT 'options for transaction like: TimeoutToFail, RequestTimeout',
`custom_data` varchar(1024) DEFAULT '' COMMENT 'custom data for transaction',
`next_cron_interval` int(11) default null comment 'next cron interval. for use of cron job',
`next_cron_time` datetime default null comment 'next time to process this trans. for use of cron job',
`owner` varchar(128) not null default '' comment 'who is locking this trans',
`ext_data` TEXT comment 'extra data for this trans. currently used in workflow pattern',
`result` varchar(1024) DEFAULT '' COMMENT 'result for transaction',
`rollback_reason` varchar(1024) DEFAULT '' COMMENT 'rollback reason for transaction',
PRIMARY KEY (`id`),
UNIQUE KEY `gid` (`gid`),
key `owner`(`owner`),
key `status_next_cron_time` (`status`, `next_cron_time`) comment 'cron job will use this index to query trans'
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
drop table IF EXISTS dtm.trans_branch_op;
CREATE TABLE IF NOT EXISTS dtm.trans_branch_op (
`id` bigint(22) NOT NULL AUTO_INCREMENT,
`gid` varchar(128) NOT NULL COMMENT 'global transaction id',
`url` varchar(1024) NOT NULL COMMENT 'the url of this op',
`data` TEXT COMMENT 'request body, depreceated',
`bin_data` BLOB COMMENT 'request body',
`branch_id` VARCHAR(128) NOT NULL COMMENT 'transaction branch ID',
`op` varchar(45) NOT NULL COMMENT 'transaction operation type like: action | compensate | try | confirm | cancel',
`status` varchar(45) NOT NULL COMMENT 'transaction op status: prepared | succeed | failed',
`finish_time` datetime DEFAULT NULL,
`rollback_time` datetime DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `gid_uniq` (`gid`, `branch_id`, `op`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
drop table IF EXISTS dtm.kv;
CREATE TABLE IF NOT EXISTS dtm.kv (
`id` bigint(22) NOT NULL AUTO_INCREMENT,
`cat` varchar(45) NOT NULL COMMENT 'the category of this data',
`k` varchar(128) NOT NULL,
`v` TEXT,
`version` bigint(22) default 1 COMMENT 'version of the value',
create_time datetime default NULL,
update_time datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE key `uniq_k`(`cat`, `k`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;

使用的配置参考:

#####################################################################
### dtm can be run without any config.
### all config in this file is optional. the default value is as specified in each line
### all configs can be specified from env. for example:
### MicroService.EndPoint => MICRO_SERVICE_END_POINT
##################################################################### Store: # specify which engine to store trans status
Driver: 'mysql'
Host: 'localhost'
User: 'root'
Password: '123456'
Port: 3306
Db: 'dtm' # Driver: 'boltdb' # default store engine # Driver: 'redis'
# Host: 'localhost'
# User: ''
# Password: ''
# Port: 6379 # Driver: 'postgres'
# Host: 'localhost'
# User: 'postgres'
# Password: 'mysecretpassword'
# Port: '5432'
# Db: 'postgres'
# Schema: 'public' # default value is 'public' ### following config is for only Driver postgres/mysql
MaxOpenConns: 500
MaxIdleConns: 500
ConnMaxLifeTime: 5 # default value is 5 (minutes) ### flollowing config is only for some Driver
# DataExpire: 604800 # Trans data will expire in 7 days. only for redis/boltdb.
# FinishedDataExpire: 86400 # finished Trans data will expire in 1 days. only for redis.
# RedisPrefix: '{a}' # default value is '{a}'. Redis storage prefix. store data to only one slot in cluster MicroService: # gRPC/HTTP based microservice config
Driver: 'dtm-driver-gozero' # name of the driver to handle register/discover
Target: 'etcd://localhost:2379/dtmservice' # register dtm server to this url
EndPoint: 'localhost:36790' ### the unit of following configurations is second
TransCronInterval: 3 # the interval to poll unfinished global transaction for every dtm process
TimeoutToFail: 35 # timeout for XA, TCC to fail. saga's timeout default to infinite, which can be overwritten in saga options
RetryInterval: 10 # the subtrans branch will be retried after this interval
RequestTimeout: 3 # the timeout of HTTP/gRPC request in dtm LogLevel: 'debug' # default: info. can be debug|info|warn|error
Log:
Outputs: 'stderr' # default: stderr, split by ",", you can append files to Outputs if need. example:'stderr,/tmp/test.log'
RotationEnable: 0 # default: 0
RotationConfigJSON: '{}' # example: '{"maxsize": 100, "maxage": 0, "maxbackups": 0, "localtime": false, "compress": false}' HttpPort: 36789
GrpcPort: 36790
JsonRpcPort: 36791 ### advanced options
UpdateBranchAsyncGoroutineNum: 1 # num of async goroutine to update branch status
TimeZoneOffset: '+8' #default '' using system default. '+8': Asia/Shanghai; '0': GMT
AdminBasePath: '' #default '' set admin access base path # ConfigUpdateInterval: 10 # the interval to update configuration in memory such as topics map... (seconds)
# TimeZoneOffset: '' # default '' using system default. '+8': Asia/Shanghai; '0': GMT
# AlertRetryLimit: 3 # default 3; if a transaction branch has been retried 3 times, the AlertHook will be called
# AlertWebHook: '' # default ''; sample: 'http://localhost:8080/dtm-hook'. this hook will be called like this:
## curl -H "Content-Type: application/json" -d '{"gid":"xxxx","status":"submitted","retry_count":3}' http://localhost:8080/dtm-hook

  1)指定使用了MySQL作为数据存储层

2)开启微服务的支持MicroService,并选择了etcd

这样服务已经启动了之后就可以参考官方文档进行一些demo测试和与项目的结合使用了

官方文档: https://dtm.pub/

文档中讲解的很细致,并且都有中文翻译, 还有一些接入的例子,

结合go-zero使用的实例:

分布式事务之dtm的更多相关文章

  1. 分布式事务 | 使用DTM 的Saga 模式

    DTM 简介 前面章节提及的MassTransit.dotnetcore/CAP都提供了分布式事务的处理能力,但也仅局限于Saga和本地消息表模式的实现.那有没有一个独立的分布式事务解决方案,涵盖多种 ...

  2. 聊一聊如何用C#轻松完成一个SAGA分布式事务

    背景 银行跨行转账业务是一个典型分布式事务场景,假设 A 需要跨行转账给 B,那么就涉及两个银行的数据,无法通过一个数据库的本地事务保证转账的 ACID ,只能够通过分布式事务来解决. 市面上使用比较 ...

  3. .NetCore中使用分布式事务DTM的二阶段消息

    一.概述 二阶段消息是DTM新提出的,可以完美代替现有的事务消息和本地消息表架构.无论从复杂度.性能.便利性还是代码量都是完胜现有的方案. 相比现有的消息架构借助于各种消息中间件比如RocketMQ等 ...

  4. 第三代微服务架构:基于 Go 的博客微服务实战案例,支持分布式事务

    这是一个可一键部署在 Kubernetes-Istio 集群中的,基于 Golang 的博客微服务 Demo,支持分布式事务. 项目地址:https://github.com/jxlwqq/blog- ...

  5. 聊一聊如何用C#轻松完成一个TCC分布式事务

    背景 银行跨行转账业务是一个典型分布式事务场景,假设 A 需要跨行转账给 B,那么就涉及两个银行的数据,无法通过一个数据库的本地事务保证转账的 ACID ,只能够通过分布式事务来解决. 在 聊一聊如何 ...

  6. 带你十天轻松搞定 Go 微服务之大结局(分布式事务)

    序言 我们通过一个系列文章跟大家详细展示一个 go-zero 微服务示例,整个系列分十篇文章,目录结构如下: 环境搭建 服务拆分 用户服务 产品服务 订单服务 支付服务 RPC 服务 Auth 验证 ...

  7. go-zero微服务实战系列(十、分布式事务如何实现)

    在分布式应用场景中,分布式事务问题是不可回避的,在目前流行的微服务场景下更是如此.比如在我们的商城系统中,下单操作涉及创建订单和库存扣减操作两个操作,而订单服务和商品服务是两个独立的微服务,因为每个微 ...

  8. [跨数据库、微服务] FreeSql 分布式事务 TCC/Saga 编排重要性

    前言 FreeSql 支持 MySql/SqlServer/PostgreSQL/Oracle/Sqlite/Firebird/达梦/Gbase/神通/人大金仓/翰高/Clickhouse/MsAcc ...

  9. 群集中的MS DTC分布式事务协调器

    MS DTC在大多数SQL 服务器下都需要安装,若只是安装数据库引擎或Analysis 服务可不安装DTC.如果后需要使用分布式事务,则可在SQL Server群集安装完成后再安装DTC. 一.群集M ...

  10. 事务使用中如何避免误用分布式事务(System.Transactions.TransactionScope)

    1:本地事务DbTransaction和分布式事务TransactionScope的区别: 1.1:System.Data.Common.DbTransaction: 本地事务:这个没什么好说了,就是 ...

随机推荐

  1. Postman Code Java-Unirest 代码的依赖

    本来是Postman的Code直接使用的,结果根据这个名字 Unirest,搜出来了很多依赖,使用了排名第一的, https://search.maven.org/search?q=Unirest 结 ...

  2. PlugIR:开源还不用微调,首尔大学提出即插即用的多轮对话图文检索 | ACL 2024

    即插即用的PlugIR通过LLM提问者和用户之间的对话逐步改进文本查询以进行图像检索,然后利用LLM将对话转换为检索模型更易理解的格式(一句话).首先,通过重新构造对话形式上下文消除了在现有视觉对话数 ...

  3. 【YashanDB知识库】设置归档日志上限,但归档日志没自动清理,导致磁盘空间满

    问题现象 客户使用一主一备做性能压测,主备机上设置了归档日志清理上下限: ARCH_CLEAN_LOWER_THRESHOLD=12G ARCH_CLEAN_UPPER_THRESHOLD=16G 但 ...

  4. Tenzing and Random Operations CF1842G 题解

    [1] 分析 设 \(m\) 次选的位置分别为 \(b_{1\sim m}\). 于是答案为 \(\mathbb E(\prod\limits_{i = 1}^{n}(a_i + \sum\limit ...

  5. 致敬传奇 Kruskal 重构树题硬控我三小时

    NOI2018 归程 存边的数组拿来干两件事,忘了清空了,其实最好开两个的 dfs 没开 vis 导致不知道为什么出现的绕圈 倍增的 fa[i][j] 定义的时候前面是 \(2^{i}\) 写着写着记 ...

  6. Kubernetes集群安装(十三)

    为了根据最新的集群特性,我们这里安装目前最新的版本 v1.19.3,如果你是在生产环境使用,建议使用上一个版本中最大的修正版本,比如 v1.15.5,由于 v1.16 版本之后和之前的版本有很大变化, ...

  7. 2023年第十二届数据技术嘉年华(DTC)资料分享

    第十二届数据技术嘉年华(DTC 2023)已于4月8日在北京圆满落幕,大会围绕"开源·融合·数智化--引领数据技术发展,释放数据要素价值"这一主题,共设置有1场主论坛,12场专题论 ...

  8. iOS程序内语言切换使用小结

    随着时代的发展,应用程序相继出现了不同语言的版本方案,中文,英文,法文,韩文等等:想在应用程序中实现语言的自由切换,需要配置多个语言的文件,根据用户的动态选择获取不同语言文件下的语言文件,从而显示到界 ...

  9. axios有没有做过⼀些业务封装?

    啊,有的,在项⽬⾥⾯我主要是封装过axios的拦截器部分 我在请求拦截器⾥⾯做了注⼊全局token的事情,这个事⼉是因为有很多接⼝都需要这个token来做数据 鉴权,为了避免书写多次 统⼀配置了⼀下 ...

  10. Fluent Operator v2.0 发布:Fluent Bit 新的部署方式——Fluent Bit Collector

    2019 年 1 月 21 日,KubeSphere 社区为了满足以云原生的方式管理 Fluent Bit 的需求开发了 FluentBit Operator.此后产品不断迭代,在 2021 年 8 ...