Laravel 延遲佇列

bestcyt發表於2019-06-24

場景示例:釋出一篇文章或者任務,設定了上架時間,那麼當上架時間到的時候,自動改變文章狀態

思路:使用laravel延遲佇列

Demo:文章狀態改變(可直接複製程式碼執行)

1.準備:

  1. 使用Redis做佇列驅動 ,開啟Redis-server redis.conf
  2. 建立任務檔案php artisan make:job endTask

2.編碼:

web.php 路由

Route::get('/index', 'PostController@index');
Route::post('/posts', 'PostController@store');

PostController

    public function index()
    {
        return view('index');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title'=>'required',
            'body'=> 'required',
        ]);
        $post['title'] = $request->title;
        $post['body'] = $request->body;
        $post['beginTime'] = Carbon::now()->addMinutes(1);
        $resPost = Post::create($post);

        //延時佇列 更新文章狀態
        endTask::dispatch($resPost)->delay($resPost->beginTime);
        return redirect()->back()->with('status', 'Your post has been submitted successfully');
    }

Post.php 模型檔案

class Post extends Model
{
    //
    protected $table = 'posts';
    protected $fillable = ['title','body','beginTime','endTime'];
}

inde.blade.php 表單

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width">
    <title>Laravel Queues</title>
    <meta name="description" content="">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <div class="col-md-5">
        <h4 class="page-header">Laravel Queues </h4>
        @foreach ($errors->all() as $error)
            <p class="alert alert-danger">{{ $error }}</p>
        @endforeach
        @if (session('status'))
            <div class="alert alert-success">
                {{ session('status')}}
            </div>
        @endif
        <form class="form-vertical" role="form" method="post" action="/posts">
            {{csrf_field()}}
            <div class="form-group">
                <input type="text" name="title" class="form-control" placeholder="Title">
            </div>
            <div class="form-group">
                <textarea class="form-control" rows="5" name="body" class="form-control" placeholder="Content"></textarea>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-info">Submit Post</button>
            </div>
        </form>
    </div>
</div>
</body>
</html>

endTask佇列

    public $post ;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Post $post)
    {
        //
        $this->post = $post;
        Log::info('post handel postId __construct: '.$this->post->id);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $res = Post::where('id',$this->post->id)->update(['status'=>2]); //更新文章的狀態
        Log::info('post handel '.$this->post->id.'-status:'.$res);
    }

3.監聽佇列:

php artisan queue:work --daemon
遇到的坑:

一開始使用php artisan queue:work,取不到資料,後來換listen就可以了,主要是work是執行單次,對延遲佇列不適用,查資料後使用了queue:work --daemon,這是三種佇列啟動監聽的區別分析

堅持開源,堅持分享:)(bestcyt)

相關文章