欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

rabbitmq direct 模式

程序员文章站 2024-03-13 22:34:16
...

1.product 

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/24
 * Time: 14:31
 */
require_once  'vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;

$exchange = 'direct_exchange';
$connection = new AMQPStreamConnection('192.168.1.103', 5672, 'zyw', '123456', '/');
$channel = $connection->channel();
$channel->exchange_declare($exchange,'direct',false,false,false);
for($i=0;$i<100;$i++) {
    $data= array('name'=>'zyw'.$i,'time'=>time(),'i'=>$i);
    $msg = new AMQPMessage(json_encode($data));
    $channel->basic_publish($msg,$exchange,'direct');
}
$channel->close();
$connection->close();

2.consume

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/24
 * Time: 14:31
 */
require_once  'vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;

$exchange = 'direct_exchange';
$connection = new AMQPStreamConnection('192.168.1.103', 5672, 'zyw', '123456', '/');
$channel = $connection->channel();
$channel->exchange_declare($exchange,'direct',false,false,false);
$queue_name='direct';
$channel->queue_declare($queue_name, false, false, true, false);

$channel->queue_bind($queue_name, $exchange, 'direct');
echo " [*] Waiting for logs. To exit press CTRL+C\n";

$callback = function ($msg) {
    echo ' [x] ', $msg->delivery_info['routing_key'], ':', $msg->body, "\n";
   $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};

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

while ($channel->is_consuming()) {
    $channel->wait();
}

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

 

相关标签: 服务器搭建