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。