LoginSignup
14
13

More than 5 years have passed since last update.

Laravel5.3のQueue非同期処理 (AWS3へ画像アップロード)

Last updated at Posted at 2016-11-02

Queue は、直訳すると「順番を待つ人や乗り物の列 」という意味です。

Laravel では、時間のかかる処理やなどを非同期で実行したい場合になどに使います。

今回は、AmazonS3へのアップロードをLaravel5.3のQueueで実装してみました。

必要な Composer package (composer require コマンド)

  • composer require aws/aws-sdk-php
  • composer require league/flysystem-aws-s3-v3

AWS3の設定

  • config/filesystems.phpcloudキーをs3
  • AWS3でBucket作成
  • disksキーの中身を、作成したBucketに合わせて変更 

ジョブクラスの作成・実装

  • php artisan queue:table => jobsテーブル(未実行なjobを格納する)を作成

  • php artisan queue:failed-table => failed_jobsテーブル(実行に失敗したjobを格納する)を作成

  • php artisan make:job UploadImage

すると app/Jobs配下にUploadImage.phpが作られるので、以下のような感じにする

<?php

namespace App\Jobs;

use App\Models\Channel;

use File;
use Storage;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class UploadImage implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public $channel;

    public $fileId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Channel $channel, $fileId)
    {
        $this->channel = $channel;
        $this->fileId = $fileId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $path = storage_path() . '/uploads/' . $this->fileId;
        $fileName = $this->fileId . '.png';

        if(Storage::disk('s3images')->put('profile/' . $fileName, fopen($path, 'r+'))) {
            File::delete($path);
        }

        $this->channel->image_fullname = $fileName;
        $this->channel->save();
    }
}

あとは、適当に画像アップロードしてあげて、受け取ったメソッド内でdispatchヘルパーを使って

$this->dispatch(new UploadImage($channel, $fileId));

みたいにしてあげればいい。

php artisan queue:workを実行すると、リスナー的なのが走り、dispatchされたjobが自動的に実行される。

queueは他にも、例えばメールをバックグラウンドで送信したい場合などに使える。

14
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13