学習備忘ログ

よく使うコードや設定のメモ

複数のワーカで処理する際の最後の処理をredisで制御する方法

課題

  • ワーカを利用し分散処理した際し、最後の処理が終わったタイミングでメールを送信したい場合

対処方法

<?php

public function handle(MediaService $mediaService)
    {
        Log::info(Utils::getLogStatusStrings() . "Create Media Job Start.");

        //既にキューが実行済みか確認
        $isExecuted = Cache::tags($this->jobId)->has($this->storeId);
        if ($isExecuted) {
            Log::info('isExecuted');
            return;
        }
        Cache::tags($this->jobId)->put($this->storeId, '', 60 * 24);

        try {
             //
        } catch(Throwable $e) {
            //
        } catch(LocationIdNullException $e) {
            //
        }

        Cache::tags($this->jobId)->put($this->storeId, $message, 60 * 24);
        if ($this->isLastQueue($this->jobId)) {
            $this->notifyResult($this->jobId);
            Cache::forget($this->jobId);
        }
        Log::info(Utils::getLogStatusStrings() . "Create Media Job End.");
    }

    //最後のキューか確認
    private function isLastQueue(string $jobId): bool
    {
        $currentNum = (int) Cache::increment($jobId);
        return $this->total === $currentNum;
    }
  • 別解としてFIFOのSQSを使うという方法があるが、その方法だと処理スピードが遅くなるので今回は除いている。