1.composer安装amqp包
composer requirer php-amqplib/php-amqplib
2.新建配置文件 config/rabbit_mq.php
return [
'host'=>'127.0.0.1',
'port'=>'5672',
'user'=>'guest',
'password'=>'guest',
'vhost'=>'/',
'exchange_name' => 'email_exchange',
'queue_name' => 'email_queue',
'route_key' => 'email_route',
'consumer_tag' => 'consumer',
];
3. 生产者Producer.php
<?php
namespace app;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;
class Producer
{
private $connection;
private $channel;
private $mq_config;
public function __construct()
{
$this->mq_config = config('rabbit_mq');
$this->connection = new AMQPStreamConnection(
$this->mq_config['host'],
$this->mq_config['port'],
$this->mq_config['user'],
$this->mq_config['password']
);
//创建通道
$this->channel = $this->connection->channel();
}
public function send($data)
{
/**
* 创建队列(Queue)
* name: hello // 队列名称
* passive: false // 如果设置true存在则返回OK,否则就报错。设置false存在返回OK,不存在则自动创建
* durable: true // 是否持久化,设置false是存放到内存中的,RabbitMQ重启后会丢失;设置true,则代表是一个持久化的队列,服务重启后也会存在,因为服务会把持久化的queue存放到磁盘上当服务重启的时候,会重新加载之前被持久化的queue
* exclusive: false // 是否排他,指定该选项为true则队列只对当前连接有效,连接断开后自动删除