sobhanatar / idempotent
用于 Laravel 的幂等性包
Requires
- php: ~7.4|~8
- ext-json: *
- ext-pdo: *
- malkusch/lock: ^2.2
- spatie/async: ^1.5
Requires (Dev)
- ext-redis: *
- orchestra/testbench: ^6.23
This package is auto-updated.
Last update: 2024-09-23 21:22:11 UTC
README
幂等包为您的 Laravel 包提供幂等性。然而,在其当前状态下,可能无法扩展到不同的需求,但可以作为实现示例。此外,本包将进行更新,旨在对其各个方面提供更多控制。
安装
要开始使用,请通过 Composer 包管理器安装 Idempotent 包
$ composer require sobhanatar/idempotent
Idempotent 服务提供者注册了自己的配置、语言和数据库迁移文件,因此您需要导出它们
$ php artisan vendor:publish --provider="Sobhanatar\Idempotent\IdempotentServiceProvider"
注意:如果您不想使用 mysql 数据库作为共享内存,可以使用以下命令发布配置和语言文件
$ php artisan vendor:publish --tag=idempotent-config --tag=idempotent-language
部署 Idempotent
要使用 idempotent 包,您需要在配置和语言文件中设置符合您的服务需求选项。配置文件有自带的文档说明,您可以通过它找到所需的信息。
下一步是决定如何控制您服务中的幂等性。Idempotent 包提供了两个中间件来帮助您实现幂等性;IdempotentHeader
和 VerifyIdempotent
。不要忘记在 Kernel.php
中注册中间件。
IdempotentHeader
IdempotentHeader
根据实体配置生成幂等性键/哈希,并将其放入请求头中。该中间件的假设是开发者将负责使用幂等性头的逻辑。
VerifyIdempotent
VerifyIdempotent
处理使端点幂等的所有必要步骤。步骤如下
- 获取
entity
配置 - 根据实体配置创建幂等性键/哈希。
- 检查幂等性键/哈希是否存在于选定的
storage
中。 - 如果不存在
- 创建一个新的状态为
progress
的记录,包含实体的timeout
,然后继续执行服务的逻辑 - 当代码执行完成后,更新缓存的响应的
status
和response
。
- 创建一个新的状态为
- 如果存在
- 如果
status
是done
或fail
,则从存储中读取response
并将其回复给用户。 - 如果
status
是progress
,则将idempotent
语言文件中该entity
的消息作为响应返回给用户。
- 如果
注意:确保只将两个中间件之一用于您希望实现幂等的路由,而不是所有路由。
清除幂等性键/哈希
如果您使用 mysql
作为存储,清除过期的键/哈希非常重要。Idempotent 包包含 idempotent:purge
Artisan 命令可以为您完成此操作。
# Purge expired keys/hashes
$ php artisan idempotent:purge --entity=my-idempotent-endpoint
您也可以在应用程序的 App\Console\Kernel
类中配置一个计划任务,以自动定期修剪您的令牌。
/** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('idempotent:purge')->hourly(); }
内部原理
本包依赖于 php-lock/lock 实现锁定机制,并使用 spatie/async 测试锁定机制。
测试
$ composer test
贡献
感谢您考虑为 Idempotent 贡献!您可以在此处阅读贡献指南。
安全
如果您发现任何与安全相关的问题,请通过电子邮件 sobhanattar@gmail.com 联系,而不是使用问题跟踪器。
致谢
许可证
幂等(Idempotent)是一个开源软件,使用MIT许可证许可。