共计 1341 个字符,预计需要花费 4 分钟才能阅读完成。
环境
1. 安装 rabbit
php 使用
安装包,直接安装 composer 安装 php-amqplib/php-amqplib 这个包
生产着
- 连接 mq server
require_once __DIR__.'/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;
$connection = new AMQPStreamConnection("127.0.0.1", 5672, "guest", "guest", "yedong_test"); // 连接 server
$channel = $connection->channel(); // 创建通道
- 创建交换机
$exchange="example_direct_exchange";
/*
name: $exchange
type: fanout 交换机类型
passive: false // don't check if an exchange with the same name exists
durable: false // the exchange won't survive server restarts // 是否是持久化
auto_delete: true //the exchange will be deleted once the channel is closed.
*/
$channel->exchange_declare($exchange, AMQPExchangeType::DIRECT, false, true, true);
3. 创建队列
// 参数
$queue = '', // 队列名称
$passive = false, // 检查是否村子啊
$durable = false, // 是否持久化
$exclusive = false, // 排外,①当前定义的队列是 connection 的 channel 是共享的,其他的 connection 是访问不到的。②当 connection 关闭的时候,队列将被删除。$auto_delete = true, // 空是自动删除
$nowait = false, //
$arguments = array(),
$ticket = null

$channel->queue_declare("test_queue_3",true,true,false,false,false,[],null);
4. 绑定队列和交换机,生成 routing_key
$channel->queue_bind("example_direct_queue_2",$exchange,"routeTest1");
5. 发送消息到队列

$msg = new AMQPMessage($i, ['content_type' => 'text/plain','delivery_mode'=>2]); //2: 持久化,重启不会丢失,默认为 1,重启会丢失
$channel->basic_publish($msg, $exchange,"routeTest1");
正文完