这篇文章主要讲解了"拉弗尔基于重置怎么实现分布式事务",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"拉弗尔基于重置怎么实现分布式事务"吧!
快速预览
安装laravel5.5 - laravel8之间的版本,然后安装快速服务化的包裹
设计者需要风醒/laravel-重置-事务开发-主
首先创建ResetProductController.php控制器,创建ResetProductModel.php模型,创建重置_事务和重置产品两张数据库表。这些操作只需要执行下面命令全部完成
phpartisanratensaction : create-examplessphpunit。可扩展标记语言增加测试套件事务
?xmlversion='1.0 '编码='UTF-8 '?phpunitxmlmlns : xsi=' http://www。w3。org/2001/XMLSchema-instance '
xsi : nonamespaceschemalocation=' ./vendor/phpunit/phpunit/phpunit。xsd '
bootstrap='vendor/autoload.php '
颜色="真"
测试套件
.testsuitename='事务'
目录。/供应商/风醒了/laravel-重置-交易/测试/目录
/testsuite
/testsuites
./phpunit最后运行测试命令。/供应商/bin/phpunit-测试套件=交易
运行结果如下所示,5个例子测试通过。
oot @ DESKTOP-vqoelj 5:/web/Linux/PHP/laravel/laravel 62 # ./供应商/bin/ph punit-test suite=transaction punit 8。5 .20由ebastianbergmannandcontributors供稿人提供.
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怎么实现分布式事务这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/77891.html
