当前位置:网站首页>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(); }}
边栏推荐
- 机器学习之数据类型案例——基于朴素贝叶斯法,用数据辩男女
- 洞见云原生|微服务及微服务架构浅析
- Pyspark de duplication dropduplicates, distinct; withColumn、lit、col; unionByName、groupBy
- 【Go实战基础】gin 如何自定义和使用一个中间件
- 2022/2/14 summary
- 京东面试官问:LEFT JOIN关联表中用ON还是WHERE跟条件有什么区别
- During MySQL installation, mysqld Exe reports that the application cannot start normally (0xc000007b)`
- Flink-使用流批一体API统计单词数量
- Taking the upgrade of ByteDance internal data catalog architecture as an example, talk about the performance optimization of business system
- Npoi export word font size correspondence
猜你喜欢
微服务实战|微服务网关Zuul入门与实战
CSDN Q & A_ Evaluation
Chrome浏览器标签管理插件–OneTab
京东面试官问:LEFT JOIN关联表中用ON还是WHERE跟条件有什么区别
"Redis source code series" learning and thinking about source code reading
Matplotlib剑客行——布局指南与多图实现(更新)
盘点典型错误之TypeError: X() got multiple values for argument ‘Y‘
Chrome浏览器插件-Fatkun安装和介绍
Don't spend money, spend an hour to build your own blog website
Flink - use the streaming batch API to count the number of words
随机推荐
「面试高频题」难度大 1.5/5,经典「前缀和 + 二分」运用题
Microservice practice | load balancing component and source code analysis
2022/2/13 summary
Watermelon book -- Chapter 6 Support vector machine (SVM)
Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
以字节跳动内部 Data Catalog 架构升级为例聊业务系统的性能优化
Essay: RGB image color separation (with code)
Matplotlib剑客行——布局指南与多图实现(更新)
数构(C语言)——第四章、矩阵的压缩存储(下)
Connect function and disconnect function of QT
Actual combat of microservices | discovery and invocation of original ecosystem implementation services
京东高级工程师开发十年,编写出:“亿级流量网站架构核心技术”
别找了,Chrome浏览器必装插件都在这了
聊聊消息队列高性能的秘密——零拷贝技术
[go practical basis] how to verify request parameters in gin
深入剖析JVM是如何执行Hello World的
Cartoon rendering - average normal stroke
Redis安装部署(Windows/Linux)
Redis sorted set data type API and application scenario analysis
JVM指令助记符