iralance / myblog

notes
0 stars 0 forks source link

rabbitmq on laravel #33

Open iralance opened 6 years ago

iralance commented 6 years ago

The Laravel queue service provides a unified API across a variety of different queue back-ends. Queues allow you to defer the processing of a time consuming task, such as sending an e-mail, until a later time which drastically speeds up web requests to your application.

install rabbitmq

mac下安装
brew update
brew install rabbitmq
或者用docker
docker pull daocloud.io/rabbitmq
docker run -d -p 5672:5672 daocloud.io/rabbitmq

安装完直接访问http://localhost:15672/ 账号密码都是guest/guest rabbitmq

using

download laravel5.5

composer create-project laravel/laravel learnlaravel5 ^5.5

Install this package via composer using:

composer require vladimir-yuldashev/laravel-queue-rabbitmq

Add these properties to .env with proper values:

QUEUE_DRIVER=rabbitmq
RABBITMQ_QUEUE=queue_name

RABBITMQ_HOST=127.0.0.1
RABBITMQ_PORT=5672
RABBITMQ_VHOST=/
RABBITMQ_LOGIN=guest
RABBITMQ_PASSWORD=guest
RABBITMQ_QUEUE=queue_name

Other AMQP transports

composer require enqueue/amqp-bunny:^0.8
<?php
// config/queue.php

return [
    'connections' => [
       'rabbitmq' => [
            'driver' => 'rabbitmq',
            'factory_class' => \Enqueue\AmqpBunny\AmqpConnectionFactory::class,
            'queue' => env('RABBITMQ_QUEUE', 'default'),
        ],
    ],
];

producer

修改web.php添加后url访问
Route::get('/push', function(){
    $data["header"] = ["q1","q2"];
    //向队列推送数据
    $job = (new Queue($data))->onConnection('rabbitmq');
    dispatch($job);
});

consumer

php artisan make:job Queue
<?php

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;

class Queue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        //用作处理消息队列内的数据
        echo json_encode($this->data);
    }
}

listen queue

php artisan queue:work rabbitmq

rabbit2

参考链接