当前位置:网站首页>DTM distributed transaction manager PHP collaboration client V0.1 beta release!!!
DTM distributed transaction manager PHP collaboration client V0.1 beta release!!!
2022-07-02 09:15:00 【Open source China Information】
https://github.com/dtm-php/dtm-client
Introduce
dtm/dtm-client It is a distributed transaction manager DTM Of PHP client , Already supported TCC Pattern 、Saga、 Distributed transaction mode of two-stage message mode , And realize and DTM Server With HTTP Agreement or gRPC Protocol communication , The client can run safely in PHP-FPM and Swoole In a collaborative environment , More right Hyperf Made more easy-to-use function support .
About DTM
DTM It's based on Go Language implementation of open source distributed transaction manager , Provide cross language , The power of combining transactions across storage engines .DTM Elegantly solved idempotent 、 Air compensation 、 Hanging equally distributed transaction problems , It also provides ease of use 、 High performance 、 A distributed transaction solution that is easy to scale horizontally .
Bright spot
- Easy to use
- Zero configuration start service , Provide very simple HTTP Interface , Greatly reduce the difficulty of starting distributed transactions
- Cross language
- It can be used by companies with multi language stack . convenient Go、Python、PHP、NodeJs、Ruby、C# And other languages .
- Easy to use
- Developers no longer worry about hanging 、 Air compensation 、 Idempotent problems , The first sub transaction barrier technology is used for processing
- Easy to deploy 、 Easy to expand
- Rely only on MySQL/Redis, Simple deployment , Easy clustering , Easy horizontal expansion
- Multiple distributed transaction protocols support
- TCC、SAGA、XA、 Phase II message , One stop solution to multiple distributed transaction problems
contrast
In Africa Java Under the language , I haven't seen anything except DTM Mature distributed transaction managers beyond , So here's going to be DTM and Java The most mature open source project in Seata comparing :
| characteristic | DTM | SEATA | remarks |
|---|---|---|---|
| Support language | Go、C#、Java、Python、PHP... | Java | DTM Easy access to a new language |
| Storage engine | Support database 、Redis、Mongo etc. | database | |
| exception handling | Sub transaction barrier automatic processing | Handle by hand | DTM Solved idempotent 、 Hang 、 Air compensation |
| SAGA Business | It's very easy to use | Complex state machine | |
| Phase II message | * | * | The simplest message final consistency architecture |
| TCC Business | * | * | |
| XA Business | * | * | |
| AT Business | It is recommended to use XA | * | AT And XA similar , But there's dirt |
| Single service multiple data sources | * | * | |
| Communication protocol | HTTP、gRPC | Dubbo Such agreement | DTM More friendly to the cloud |
| star Number | DTM from 2021-06-04 Release 0.1 edition , Rapid development |
From the characteristics of the above comparison ,DTM It has great advantages in many aspects . If you consider multilingual support 、 Multi storage engine support , that DTM It is undoubtedly your first choice .
install
adopt Composer It's very easy to install dtm-client
composer require dtm/dtm-client- Don't forget to start when using DTM Server Oh
To configure
The configuration file
If you are in Hyperf Use... In the framework , After installing the components , This can be done by vendor:publish Command a release configuration file on ./config/autoload/dtm.php
php bin/hyperf.php vendor:publish dtm/dtm-client If you are in Africa Hyperf Use... In the framework , Replicable ./vendor/dtm/dtm-client/publish/dtm.php File to the corresponding configuration directory .
use DtmClient\\Constants\\Protocol;use DtmClient\\Constants\\DbType;return [ // The client and DTM Server Communication protocol , Support Protocol::HTTP and Protocol::GRPC Two kinds of 'protocol' => Protocol::HTTP, // DTM Server The address of 'server' => '127.0.0.1', // DTM Server The port of 'port' => [ 'http' => 36789, 'grpc' => 36790, ], // Sub transaction barrier configuration 'barrier' => [ // DB Sub transaction barrier configuration in mode 'db' => [ 'type' => DbType::MySQL ], // Redis Sub transaction barrier configuration in mode 'redis' => [ // Timeout of sub transaction barrier record 'expire_seconds' => 7 * 86400, ], // Not Hyperf Classes that apply sub transaction barriers under the framework 'apply' => [], ], // HTTP Under the agreement Guzzle General configuration of the client 'guzzle' => [ 'options' => [], ],];Configuration middleware
Before use , Need configuration DtmClient\\Middleware\\DtmMiddleware Middleware as Server Global middleware , The middleware supports PSR-15 standard , It can be applied to all frameworks supporting the specification .
stay Hyperf Refer to Hyperf file - middleware chapter .
Use
dtm-client Is very simple to use , We provide a sample project dtm-php/dtm-sample To help you better understand and debug .
Before using this component , It is also strongly recommended that you read DTM Official documents , For a more detailed understanding .
TCC Pattern
TCC Pattern is a very popular flexible transaction solution , from Try-Confirm-Cancel The acronyms of three words are composed of TCC The concept of , The first is the Pat Helland On 2007 A piece published in was called 《Life beyond Distributed Transactions:an Apostate’s Opinion》 In my paper, I put forward .
TCC Of 3 Stages
Try Stage : Trying to perform , Complete all business checks ( Uniformity ), Reserve necessary business resources ( Quasi isolation )
Confirm Stage : If all branches Try It's all done , Go to Confirm Stage .Confirm Really do business , No business checks , Use only Try Business resources reserved in the stage
Cancel Stage : If all branches Try One failed , Go to Cancel Stage .Cancel Release Try Business resources reserved in the stage .
If we want to carry out a business similar to inter-bank transfer , Transfer out (TransOut) And transfer in (TransIn) In different microservices , A successful TCC A typical sequence diagram of a transaction is as follows :

Code example
The following is shown in Hyperf How to use it in the framework , Other frameworks are similar
<?phpnamespace App\\Controller;use DtmClient\\TCC;use DtmClient\\TransContext;use Hyperf\\Di\\Annotation\\Inject;use Hyperf\\HttpServer\\Annotation\\Controller;use Hyperf\\HttpServer\\Annotation\\GetMapping;use Throwable;#[Controller(prefix: '/tcc')]class TccController{ protected string $serviceUri = 'http://127.0.0.1:9501'; #[Inject] protected TCC $tcc; #[GetMapping(path: 'successCase')] public function successCase() { try { $this->tcc->globalTransaction(function (TCC $tcc) { // Create sub transactions A Call data for $tcc->callBranch( // call Try Method parameters ['amount' => 30], // Try Methodical URL $this->serviceUri . '/tcc/transA/try', // Confirm Methodical URL $this->serviceUri . '/tcc/transA/confirm', // Cancel Methodical URL $this->serviceUri . '/tcc/transA/cancel' ); // Create sub transactions B Call data for , And so on $tcc->callBranch( ['amount' => 30], $this->serviceUri . '/tcc/transB/try', $this->serviceUri . '/tcc/transB/confirm', $this->serviceUri . '/tcc/transB/cancel' ); }); } catch (Throwable $e) { var_dump($e->getMessage(), $e->getTraceAsString()); } // adopt TransContext::getGid() get Global transaction ID And back to return TransContext::getGid(); }}Saga Pattern
Saga Pattern is one of the most famous solutions in the field of distributed transactions , It is also very popular in major systems , It first appeared in 1987 year from Hector Garcaa-Molrna & Kenneth Salem Published papers SAGAS in .
Saga It is a final consistency transaction , It's also a flexible transaction , It's also called Long running transactions (Long-running-transaction),Saga It consists of a series of local transactions . After each local transaction updates the database , Will release a message or an event to trigger Saga Execution of the next local transaction in the global transaction . If a local transaction fails because some business rules cannot be met ,Saga It will perform the compensation operation of all transactions successfully committed before this failed transaction . therefore Saga Patterns are contrasting TCC Mode time , Due to the lack of resource reservation steps , It often becomes more troublesome when implementing rollback logic .
Saga Sub transaction splitting
For example, we need to carry out a business similar to bank inter-bank transfer , take A In the account 30 Yuan transferred to B Account , according to Saga How things work , We will deal with the overall situation , Split into the following services :
- Transfer out (TransOut) service , Here will be the operation A Account deduction 30 element
- Transfer out compensation (TransOutCompensate) service , Rollback the above transfer out operation , namely A Account increase 30 element
- into (TransIn) service , There will be B Account increase 30 element
- Transfer out compensation (TransInCompensate) service , Rollback the above transfer in operation , namely B The accounts are down 30 element
The logic of the whole transaction is :
Transfer out succeeded => Execution transfer succeeded => Global transaction completed
If an error occurs in the middle , For example, transfer in B An error occurred in the account , Then the compensation operation of the executed branch will be called , namely :
Transfer out succeeded => Failed to execute transfer in => Successful implementation of transfer in compensation => Successfully execute transfer out compensation => Global transaction rollback completed
Here is a successful SAGA A typical sequence diagram of a transaction :

Code example
The following is shown in Hyperf How to use it in the framework , Other frameworks are similar
namespace App\\Controller;use DtmClient\\Saga;use DtmClient\\TransContext;use Hyperf\\Di\\Annotation\\Inject;use Hyperf\\HttpServer\\Annotation\\Controller;use Hyperf\\HttpServer\\Annotation\\GetMapping;#[Controller(prefix: '/saga')]class SagaController{ protected string $serviceUri = 'http://127.0.0.1:9501'; #[Inject] protected Saga $saga; #[GetMapping(path: 'successCase')] public function successCase(): string { $payload = ['amount' => 50]; // initialization Saga Business $this->saga->init(); // Add transfer out sub transaction $this->saga->add( $this->serviceUri . '/saga/transOut', $this->serviceUri . '/saga/transOutCompensate', $payload ); // Add transfer in sub transaction $this->saga->add( $this->serviceUri . '/saga/transIn', $this->serviceUri . '/saga/transInCompensate', $payload ); // Submit Saga Business $this->saga->submit(); // adopt TransContext::getGid() get Global transaction ID And back to return TransContext::getGid(); }}边栏推荐
- "Redis source code series" learning and thinking about source code reading
- [staff] common symbols of staff (Hualian clef | treble clef | bass clef | rest | bar line)
- 数构(C语言--代码有注释)——第二章、线性表(更新版)
- Mysql安装时mysqld.exe报`应用程序无法正常启动(0xc000007b)`
- Gocv split color channel
- There is a problem with MySQL installation (the service already exists)
- Chrome浏览器标签管理插件–OneTab
- Knowledge points are very detailed (code is annotated) number structure (C language) -- Chapter 3, stack and queue
- 数构(C语言)——第四章、矩阵的压缩存储(下)
- Double non undergraduate students enter the factory, while I am still quietly climbing trees at the bottom (Part 1)
猜你喜欢

Redis zadd导致的一次线上问题排查和处理

C language - Blue Bridge Cup - 7 segment code

WSL installation, beautification, network agent and remote development

十年开发经验的程序员告诉你,你还缺少哪些核心竞争力?

《统计学习方法》——第五章、决策树模型与学习(上)

Oracle modify database character set

C4D quick start tutorial - C4d mapping

Taking the upgrade of ByteDance internal data catalog architecture as an example, talk about the performance optimization of business system

微服务实战|Eureka注册中心及集群搭建

C language implementation of mine sweeping game
随机推荐
Hengyuan cloud_ Can aiphacode replace programmers?
使用IBM MQ远程连接时报错AMQ 4043解决思路
Cloudrev self built cloud disk practice, I said that no one can limit my capacity and speed
Chrome浏览器标签管理插件–OneTab
Microservice practice | teach you to develop load balancing components hand in hand
"Redis source code series" learning and thinking about source code reading
Pyspark de duplication dropduplicates, distinct; withColumn、lit、col; unionByName、groupBy
C4D quick start tutorial - C4d mapping
[staff] time mark and note duration (staff time mark | full note rest | half note rest | quarter note rest | eighth note rest | sixteenth note rest | thirty second note rest)
Gocv image reading and display
A detailed explanation takes you to reproduce the statistical learning method again -- Chapter 2, perceptron model
Move a string of numbers backward in sequence
Using recursive functions to solve the inverse problem of strings
[go practical basis] how to customize and use a middleware in gin
C# 将网页保存为图片(利用WebBrowser)
数构(C语言--代码有注释)——第二章、线性表(更新版)
Leetcode sword finger offer brush questions - day 23
"Interview high frequency question" is 1.5/5 difficult, and the classic "prefix and + dichotomy" application question
Cloudreve自建云盘实践,我说了没人能限制得了我的容量和速度
How to realize asynchronous programming in a synchronous way?