laravel使用rabbitMQ简单示例

windows安装rabbitMQ:https://blog.csdn.net/m0_61083409/article/details/123790124

安装 PHP amqp 扩展:https://blog.csdn.net/m0_62199749/article/details/123687980?spm=1001.2014.3001.5502

php -m,看是否安装成功

 

开启 PHP sockets:https://blog.csdn.net/m0_62199749/article/details/123688943?spm=1001.2014.3001.5502

参考以上连接安装的扩展

1、Composer 安装laravel扩展

composer require vladimir-yuldashev/laravel-queue-rabbitmq

2 、在 config/queue.php 配置文件中的 connections 数组中加入以下配置

'rabbitmq' => [

        'driver' => 'rabbitmq',
        'queue' => env('RABBITMQ_QUEUE', 'default'),
        'connection' => PhpAmqpLib\Connection\AMQPLazyConnection::class,

        'hosts' => [
            [
                'host' => env('RABBITMQ_HOST', '127.0.0.1'),
                'port' => env('RABBITMQ_PORT', 5672),
                'user' => env('RABBITMQ_USER', 'guest'),
                'password' => env('RABBITMQ_PASSWORD', 'guest'),
                'vhost' => env('RABBITMQ_VHOST', '/'),
            ],
        ],

        'options' => [
            'ssl_options' => [
                'cafile' => env('RABBITMQ_SSL_CAFILE', null),
                'local_cert' => env('RABBITMQ_SSL_LOCALCERT', null),
                'local_key' => env('RABBITMQ_SSL_LOCALKEY', null),
                'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true),
                'passphrase' => env('RABBITMQ_SSL_PASSPHRASE', null),
            ],
            'queue' => [
                'job' => VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Jobs\RabbitMQJob::class,

                /*//以下配置是rabbitmq 广播模式(direct)
                'exchange' => 'laravel_exchange2',
                'exchange_type' => 'direct',
                'exchange_routing_key' => 'userkey1',*/

                /*//以下配置是rabbitmq 广播模式(topic)
                'exchange' => 'laravel_exchange1',
                'exchange_type' => 'topic',
                'exchange_routing_key' => 'user.info',*/
            ],
        ],

        /*
         * Set to "horizon" if you wish to use Laravel Horizon.
         */
        'worker' => env('RABBITMQ_WORKER', 'default'),

    ],

 3、修改.env文件

#增加rabbitmq
QUEUE_DRIVER=rabbitmq
RABBITMQ_HOST=127.0.0.1
RABBITMQ_PORT=5672
RABBITMQ_VHOST=test-host
RABBITMQ_USER=guest
RABBITMQ_PASSWORD=guest

有两种方法使用rabbitmq

一、第一种直接像laravel使用redis队列一样

1.创建任务类

php artisan make:job rabbitmqQueue

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class rabbitmqQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        sleep(5);
        Log::info($this->data);
    }
}

2、路由请求发布任务

Route::get('/queue', function () {
    \App\Jobs\rabbitmqQueue1::dispatch('ce shi')->onConnection('rabbitmq')->onQueue('host-queue1');
});

可以看到如图

3、执行如下命令进行监听消费

php artisan queue:work rabbitmq --queue=host-queue1

 二、第二种直接入队列进行消费

1、新建连接的工具类

<?php

namespace App\Common\Utill;

use Illuminate\Support\Facades\Log;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class Rabbitmq{
    //取得rabbitmq连接
    public static function getConnect()    {
        $config = [
            'host' => env('RABBITMQ_HOST', '127.0.0.1'),
            'port' => env('RABBITMQ_PORT', 5672),
            'user' => env('RABBITMQ_USER', 'guest'),
            'password' => env('RABBITMQ_PASSWORD', 'guest'),
            'vhost' => env('RABBITMQ_VHOST', '/'),
        ];

        return new AMQPStreamConnection($config["host"],$config["port"],$config["user"],$config["password"],$config["vhost"]);
    }
    //推送到消息队列
    public static function push($queue,$messageBody,$exchange='router')    {
        $connection = self::getConnect();
        $channel = $connection->channel();
        //声明一个队列
        $channel->queue_declare($queue,false,true,false,false);
        $channel->exchange_declare($exchange,'direct',false,true,false);
        $channel->queue_bind($queue,$exchange);
        $message = new  AMQPMessage($messageBody,array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
        $channel->basic_publish($message,$exchange);
        $channel->close();
        $connection->close();
    }
    
    //进行消费测试
    public static function consumeTest($queue){
        $connection = self::getConnect();
        $channel = $connection->channel();

        echo ' [*] Waiting for logs. To exit press CTRL+C', "\n";

        $callback = function($msg){
            echo ' [x] ', $msg->body, "\n";
        };

        $channel->basic_consume($queue, '', false, true, false, false, $callback);

        while(count($channel->callbacks)) {
            $channel->wait();
        }

        $channel->close();
        $connection->close();
    }
}

2、生成命令文件进行消费

php artisan make:command rabbitmqConsumeTest

<?php

namespace App\Console\Commands;

use App\Common\Utill\Rabbitmq;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class rabbitmqConsumeTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rabbitmqConsumeTest';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'rabbitmq测试';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Rabbitmq::consumeTest("test-queue");
    }
}

3、路由请求发布任务

Route::get('/queue', function () {
    $user = User::query()->find(1);
    Rabbitmq::push('test-queue',$user);
});

4、执行命令消费信息

 php artisan rabbitmqConsumeTest

5、查看结果 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值