这篇文章主要讲解了“Laravel基于reset怎么实现分布式事务”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Laravel基于reset怎么实现分布式事务”吧!
安装laravel5.5 - laravel8之间的版本,然后安装快速服务化的package
composer require windawake/laravel-reset-transaction dev-master
首先创建ResetProductController.php控制器,创建ResetProductModel.php模型,创建reset_transaction和reset_product两张数据库表。这些操作只需要执行下面命令全部完成
php artisan resetTransact:create-examples
phpunit.xml增加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>
最后运行测试命令 ./vendor/bin/phpunit --testsuite=Transaction
运行结果如下所示,5个例子测试通过。
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)
开箱即用,不需要重构原有项目的代码,与mysql事务写法一致,简单易用。
支持http协议的服务化接口,想要支持其它协议则需要重写中间件。
支持读已提交,可重复读,与mysql的事务隔离级别同步。
看过《明日边缘》电影就会知道,存档和读档的操作。这个分布式事务组件仿造《明日边缘》电影的原理,每次请求基础服务一开始时读档,然后继续后面的操作,结束时所有操作全部回滚并且存档,最后commit把存档全部执行成功。整个过程是遵守两段提交协议,先prepare,最后commit。
以vendor/windawake/laravel-reset-transaction/tests/TransactionTest.php
文件为例子
<?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();
}}
感谢各位的阅读,以上就是“Laravel基于reset怎么实现分布式事务”的内容了,经过本文的学习后,相信大家对Laravel基于reset怎么实现分布式事务这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。