> Laravel的會話阻止機制通過同時調節會議來保護種族條件和數據不一致。這確保了並發操作期間的數據完整性。
有效的會話阻止這些先決條件:
以下代碼片段演示了其基本用法:
Route::post('/endpoint', function() { // Application logic here })->block($lockSeconds = 5, $waitSeconds = 10);現實世界應用程序:付款處理
這個精緻的實現:
<?php namespace App\Http\Controllers; use App\Models\Payment; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\Exceptions\PaymentException; class PaymentController extends Controller { public function process(Request $request) { return DB::transaction(function() use ($request) { // Verify payment existence and unprocessed status $payment = Payment::findOrFail($request->payment_id); if ($payment->isProcessed()) { throw new PaymentException('Payment already processed.'); } // Initiate payment processing $result = $this->paymentGateway->charge([ 'amount' => $payment->amount, 'currency' => $payment->currency, 'token' => $request->payment_token ]); $payment->markAsProcessed($result->transaction_id); return response()->json([ 'status' => 'success', 'transaction_id' => $result->transaction_id ]); }); } } // routes/api.php Route::post('/payments/process', [PaymentController::class, 'process'])->block(5, 10);
防止重複的付款處理。
以上是通過Laravel會話阻止管理並發請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!