1、laravel5.5的隊列和tp5的隊列差不多,會了其中一個另一個自然也就會了
2、redis服務器先裝好
3、laravel5 建議使用php自帶的predis包,方便協同 -- composer require predis/predis:1.0.*
4、使用參考文章:1)https://www.cnblogs.com/bing2017/p/8573230.html
2)https://www.cnblogs.com/wangzhaobo/p/10191906.html
3)https://phpartisan.cn/news/97.html
5、代碼:
控制器:
/** * use predis-list demo addby xzz 2019/09/27. * onQueue : 自定義隊列名字,避免沖突 * delay: 延遲 * php artisan queue:listen --queue queueName * @return \Illuminate\Http\Response */ public function predisList(Request $request) { $topic = \App\models\Topic::find($request->id); //dd($topic); //die; if($topic){ /* 隊列生成消費者模式:(親測成功) 調用方式: *【HomeController@index * 1、$topic = model('Topic')->find(1); * 2、dispatch(new HelloJobQueue($topic)->->onQueue('queueName')); * 3、cli:php artisan queue:listen --queue queueName 】 */ dispatch(new HelloJobQueue($topic))->delay(10)->onQueue('queueName'); } }
App\Jobs\HelloJobQueue.php -- 具體隊列job
<?php /** * 隊列生成消費者模式:(親測成功) 調用方式: *【HomeController@index 1、$topic = model('Topic')->find(1); 2、dispatch(new HelloJobQueue($topic)->->onQueue('queueName')); * 3、cli:php artisan queue:listen --queue queueName 】 * @param Topic 依賴注入$topic模型對象 * @return return_type * @author xzz 2019年9月27日 上午11:48:39 */ namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\models\Topic; use Illuminate\Support\Facades\DB; class HelloJobQueue implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $topic; /** * Create a new job instance. * * @return void */ public function __construct(Topic $topic) { // $this->topic = $topic; } /** * Execute the job. * * @return void */ public function handle() { //執行隊列業務 if($this->topic->id > 0){ // 為了避免模型監控器死循環調用,我們使用 DB 類直接對數據庫進行操作 DB::table('topics')->where('id', $this->topic->id)->update(['title'=>'predis helloJobQueue do : '.$this->topic->title]); /* 下面DB未進行死循環 */ //DB::table('topics')->where('id', $this->topic->id)->update(['title'=>'predis helloJobQueue do 111: '.$this->topic->title, 'updated_at'=>date('Y-m-d H:i:s')]); //$this->topic->save(['id'=>$this->topic->id, 'title'=>'predis helloJobQueue do : '.$this->topic->title]); $obj = Topic::find(($this->topic->id)+1); $obj->title = 'model--predis helloJobQueue do : '.$obj->title; $obj->save(); } } }
開啟php-cli: php artisan queue:listen --queue queueName --timeout 60
查看數據庫數據變更 和 php-cli 輸出
over。