PHP Framework
Laravel
Laravel advanced learning: implementing distributed transactions based on reset
Laravel advanced learning: implementing distributed transactions based on reset
The following tutorial column of Laravel will introduce to you how LLaravel implements distributed transactions based on the reset mechanism. I hope it will be helpful to everyone!
Quick preview
Install the version between laravel5.5 - laravel8, and then install the fast service package
composer require windawake /laravel-reset-transaction dev-master
First create the ResetProductController.php controller, create the ResetProductModel.php model, and create two database tables, reset_transaction and reset_product. All these operations need to be completed by executing the following commands
php artisan resetTransact:create-examples
phpunit.xmlAdd testsuite Transaction
<?xml version="1.0" encoding="UTF-8"?><phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
...... <testsuite name="Transaction">
<directory>./vendor/windawake/laravel-reset-transaction/tests</directory>
</testsuite>
</testsuites>
......</phpunit>
Finally run the test command./vendor/bin/phpunit --testsuite=Transaction
The running results are as follows, 5 examples passed the test.
oot@DESKTOP-VQOELJ5:/web/linux/php/laravel/laravel62# ./vendor/bin/phpunit --testsuite=TransactionPHPUnit 8.5.20 by Sebastian Bergmann and contributors...... 5 / 5 (100%)Time: 219 ms, Memory: 22.00 MB OK (5 tests, 5 assertions)
Functional features
It can be used out of the box, no need to reconstruct the code of the original project, it is consistent with the mysql transaction writing method, simple and easy use.
Supports the service interface of http protocol. If you want to support other protocols, you need to rewrite the middleware.
Supports read committed, repeatable reading, and is synchronized with the transaction isolation level of mysql.
Principle Analysis
Having watched the movie "Edge of Tomorrow", you will know the operations of archiving and loading. This distributed transaction component imitates the principle of the "Edge of Tomorrow" movie. Every time a basic service is requested, the file is read at the beginning, and then the subsequent operations are continued. At the end, all operations are rolled back and archived, and finally the commit is executed successfully. The whole process follows a two-stage commit protocol, first prepare and finally commit.
How to use
Take the vendor/windawake/laravel-reset-transaction/tests/TransactionTest.php file as an example
<?php
namespace Tests\Feature;use Tests\TestCase;use Illuminate\Support\Facades\DB;class TransactionTest extends TestCase{
public function testCreateWithCommit()
{
$num = rand(1, 10000);
$productName = 'php ' . $num;
$data = [
'store_id' => 1,
'product_name' => $productName,
];
// 开启分布式事务,其实是生成全局唯一id
$transactId = $this->beginDistributedTransaction();
$header = [
在header 'transact_id' => $transactId,
];
// 分布式事务内,请求都需要在request header带上transact_id
$response = $this->post('api/resetProduct', $data, $header);
$product = $response->json();
// 分布式事务提交,也是接口请求,把之前的存档记录全部处理
$this->commitDistributedTransaction($transactId);
$response = $this->get('/api/resetProduct/' . $product['pid']);
$product = $response->json();
$this->assertEquals($productName, $product['product_name']);
}
private function beginDistributedTransaction()
{
return session_create_id();
}
private function commitDistributedTransaction($transactId)
{
$response = $this->post('/api/resetTransaction/commit', [], ['transact_id' => $transactId]);
return $response->getStatusCode();
}
private function rollbackDistributedTransaction($transactId)
{
$response = $this->post('/api/resetTransaction/rollback', [], ['transact_id' => $transactId]);
return $response->getStatusCode();
}}
Personal Notes
I previously wrote the laravel rapid service package, but it did not solve the problem of data consistency. I tried to use XA, but XA can only solve the problem of multiple databases on a single machine and cannot solve the problem of servicing multiple machines. Then I tried to study tcc and seata, but after reading it, I was confused and at a loss. Being forced to a dead end, I had no choice but to create my own distributed transaction solution. For a long time, I have always thought that using MySQL alone cannot solve the problem of distributed transactions. Now I finally understand that there is still a way!
The above is the detailed content of Laravel advanced learning: implementing distributed transactions based on reset. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
How to implement a referral system in Laravel?
Aug 02, 2025 am 06:55 AM
Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,
How to use accessors and mutators in Eloquent in Laravel?
Aug 02, 2025 am 08:32 AM
AccessorsandmutatorsinLaravel'sEloquentORMallowyoutoformatormanipulatemodelattributeswhenretrievingorsettingvalues.1.Useaccessorstocustomizeattributeretrieval,suchascapitalizingfirst_nameviagetFirstNameAttribute($value)returningucfirst($value).2.Usem
What are Repository Contracts in Laravel?
Aug 03, 2025 am 12:10 AM
The Repository pattern is a design pattern used to decouple business logic from data access logic. 1. It defines data access methods through interfaces (Contract); 2. The specific operations are implemented by the Repository class; 3. The controller uses the interface through dependency injection, and does not directly contact the data source; 4. Advantages include neat code, strong testability, easy maintenance and team collaboration; 5. Applicable to medium and large projects, small projects can use the model directly.
How to use subqueries in Eloquent in Laravel?
Aug 05, 2025 am 07:53 AM
LaravelEloquentsupportssubqueriesinSELECT,FROM,WHERE,andORDERBYclauses,enablingflexibledataretrievalwithoutrawSQL;1.UseselectSub()toaddcomputedcolumnslikepostcountperuser;2.UsefromSub()orclosureinfrom()totreatsubqueryasderivedtableforgroupeddata;3.Us
How to create a RESTful API with Laravel?
Aug 02, 2025 pm 12:31 PM
Create a Laravel project and configure the database environment; 2. Use Artisan to generate models, migrations and controllers; 3. Define API resource routing in api.php; 4. Implement the addition, deletion, modification and query methods in the controller and use request verification; 5. Install LaravelSanctum to implement API authentication and protect routes; 6. Unify JSON response format and handle errors; 7. Use Postman and other tools to test the API, and finally obtain a complete and extensible RESTfulAPI.
Laravel MVC: architecture limitations
Aug 03, 2025 am 12:50 AM
Laravel'simplementationofMVChaslimitations:1)Controllersoftenhandlemorethanjustdecidingwhichmodelandviewtouse,leadingto'fat'controllers.2)Eloquentmodelscantakeontoomanyresponsibilitiesbeyonddatarepresentation.3)Viewsaretightlycoupledwithcontrollers,m
Understanding MVC: How Laravel Implements the Model-View-Controller Pattern
Aug 02, 2025 am 01:04 AM
LaravelimplementstheMVCpatternbyusingModelsfordatamanagement,Controllersforbusinesslogic,andViewsforpresentation.1)ModelsinLaravelarepowerfulORMshandlingdataandrelationships.2)ControllersmanagetheflowbetweenModelsandViews.3)ViewsuseBladetemplatingfor
How to handle recurring payments with Laravel Cashier?
Aug 06, 2025 pm 01:38 PM
InstallLaravelCashierviaComposerandconfiguremigrationandBillabletrait.2.CreatesubscriptionplansinStripeDashboardandnoteplanIDs.3.CollectpaymentmethodusingStripeCheckoutandstoreitviasetupintent.4.SubscribeusertoaplanusingnewSubscription()anddefaultpay


