?本文以lumen操作, laravel请自行参阅文档
安装:
composer require bschmitt/laravel-amqp
复制 vendor/bschmitt/laravel-amqp/config/amqp.php to config/amqp.php
编辑你的config/amqp.php 符合你的rabbitmq
编辑: bootstrap/app.php:
加入
$app->configure('amqp');
$app->register(Bschmitt\Amqp\LumenServiceProvider::class);
?这里使用lumen命令行的模式做生产者和消费者
生产者命令: app/Console/Commands/PublishAmqpCommand.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;
use Db;
use Bschmitt\Amqp\Facades\Amqp;
class PublishAmqpCommand extends Command
{
// 命令名
protected $name = 'zj:publishamqp';
// 描述
protected $description = "publish msg to mq";
/**
* 命令的名称及其签名
*
* @var string
*/
protected $signature = ' zj:publishamqp {msg}';
// 执行
public function handle()
{
//Amqp::publish('routing-key', 'message');
Amqp::publish('', $this->argument('msg') , ['queue' => 'queue-name']);
//Amqp::publish('routing-key2', 'message2' , ['exchange' => 'amq.topic']);
}
}
消费者命令:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;
use Db;
use Bschmitt\Amqp\Facades\Amqp;
class ConsumeAmqpCommand extends Command
{
// 命令名
protected $name = 'zj:consumeamqp';
// 描述
protected $description = "consume msg from mq";
// 执行
public function handle()
{
$obj = $this;
Amqp::consume('queue-name', function ($message, $resolver) use ($obj) {
$obj->info($message->body);
$resolver->acknowledge($message);
}, [
'persistent' => true, // required if you want to listen forever
]);
}
}
?修改: app/Console/Kernel.php
use App\Console\Commands\PublishAmqpCommand;
use App\Console\Commands\ConsumeAmqpCommand;
...
protected $commands = [
Other::class,
PublishAmqpCommand::class,
ConsumeAmqpCommand::class,
];
测试:
先执行消费者命令:
php artisan zj:consumeamqp
再执行生产者命令:
php artisan zj:publishamqp "hello mq"
在消费者端可以看到输出?
参考:
bschmitt/laravel-amqp - Packagist
|