业务场景:项目里边有很多视频资源需要上传到抖音资源库,通过队列一条一条上传。
参考实例:发送邮件,仅供参考
(1)创建任务【生成任务类】
在你的应用程序中,队列的任务类都默认放在 app/Jobs 目录下。如果这个目录不存在,那当你运行 make:job Artisan 命令时目录就会被自动创建。你可以用以下的 Artisan 命令来生成一个新的队列任务
php artisan make:job DyUploadResource
任务类结构
任务类的结构很简单,一般来说只会包含一个让队列用来调用此任务的 handle 方法,定义需要执行的任务逻辑,如发送邮件等
-
- namespace App\Jobs;
-
- use App\Models\HtQuestLibraryQuest;
- use Illuminate\Bus\Queueable;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Bus\Dispatchable;
- use Illuminate\Queue\InteractsWithQueue;
- class DyUploadResource implements ShouldQueue
- {
- use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
-
- /**
- * 任务最大尝试次数。
- *
- * @var int
- */
- public $tries = 5;
-
- /**
- * 任务失败前允许的最大异常数
- *
- * @var int
- */
- public $maxExceptions = 3;
-
- /**
- * 任务运行的超时时间。
- *
- * @var int
- */
- public $timeout = 600;
-
- /**
- * 课程信息
- *
- * @var int
- */
- public $product_data;
-
- /**
- * 抖音资源上传
- *
- * @return void
- */
- public function __construct(array $product_data)
- {
- $this->product_data = $product_data;
-
- if(empty($product_data)){
-
- exit();
- }
- }
-
- /**
- * Execute the job.
- * 里边写代码逻辑
- * @return bool
- */
- public function handle(): bool
- {
-
- }
-
- }
-
(2)分发任务【如何使用】
-
- namespace App\Http\Controllers;
-
- use App\Jobs\ProcessPodcast;
- use Illuminate\Http\Request;
- use App\Http\Controllers\Controller;
-
- class PodcastController extends Controller
- {
- /**
- * 抖音资源课程上传
- */
- public function dyUploadResource(Request $request)
- {
- // dispatch 用于分发,onQueue 用户起名,监听使用
- // ->delay(Carbon::now()->addMinutes(10)) 延迟分发
- DyUploadResourceMiddle::dispatch($product_data)->onQueue('dy_resource_get_status');
-
- }
- }
(3)监听队列
php artisan queue:work --queue=dy_resource_get_status
开启后队列会执行redis已入队的值

redis队列任务:
