Rumah >pembangunan bahagian belakang >tutorial php >Penyegerakan proses pengendalian dengan kunci cache laravel
inilah cara melaksanakan kunci cache:
use Illuminate\Support\Facades\Cache; $lock = Cache::lock('process-payment', 120); // Creates a lock named 'process-payment' lasting 120 seconds if ($lock->get()) { // Payment processing logic here. The lock is automatically released after 120 seconds. }mari kita menggambarkan dengan contoh praktikal pengendalian webhook:
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Cache; use App\Jobs\ProcessWebhook; use Illuminate\Http\Request; use Log; use Exception; class WebhookController extends Controller { public function handle(Request $request) { $webhookId = $request->input('webhook_id'); $lockName = "webhook-{$webhookId}"; $lock = Cache::lock($lockName, 60); try { if (!$lock->get()) { Log::info("Webhook {$webhookId} is already being processed"); return response()->json(['message' => 'Webhook is being processed'], 409); } $this->validateWebhook($request); // Validation step ProcessWebhook::dispatch($request->all(), $lock->owner())->onQueue('webhooks'); return response()->json(['message' => 'Webhook accepted', 'processing_id' => $lock->owner()]); } catch (Exception $e) { $lock?->release(); throw $e; } } } class ProcessWebhook implements ShouldQueue { public function __construct(private array $payload, private string $lockOwner) {} public function handle() { $lock = Cache::restoreLock("webhook-{$this->payload['webhook_id']}", $this->lockOwner); try { $this->processWebhookPayload(); // Webhook processing logic } finally { $lock->release(); // Ensure lock release even on errors } } }Contoh ini menunjukkan cara memperoleh kunci, memproses webhook dalam blok yang dilindungi, dan dapat melepaskan kunci, memastikan integriti data walaupun di bawah permintaan serentak. Kunci cache Laravel menyediakan mekanisme yang boleh dipercayai untuk menguruskan proses serentak dan mengekalkan kestabilan aplikasi.
Atas ialah kandungan terperinci Penyegerakan proses pengendalian dengan kunci cache laravel. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!