rabbitmq fanout模式(发布订阅)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
生产者
require_once './vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
 
$exchangeName = 'exchange_fanout_1';
// $queueName = 'queue_fanout_1';
 
$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'test', 'test', '/');
$channel = $connection->channel();
 
 
//推送成功
$channel->set_ack_handler(
    function (AMQPMessage $message) {
        echo "成功: " . $message->body . PHP_EOL;
    }
);
 
//推送失败
$channel->set_nack_handler(
    function (AMQPMessage $message) {
        echo "失败: " . $message->body . PHP_EOL;
    }
);
$channel->confirm_select();
 
 
$channel->exchange_declare($exchangeName, 'fanout', false, false, false);
 
for ($i = 0; $i < 10; $i++) {
    $msg = new AMQPMessage('消息: '.$i);
    $channel->basic_publish($msg, $exchangeName);
}
 
 
$channel->wait_for_pending_acks();
$channel->close();
$connection->close();

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
消费者
require_once './vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
 
$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'test', 'test', '/');
$channel = $connection->channel();
 
$exchangeName = 'exchange_fanout_1';
$queueName = $argv[1];
 
$channel->exchange_declare($exchangeName, 'fanout', false, false, false);
$channel->queue_declare($queueName, false, false, false, false);
$channel->queue_bind($queueName, $exchangeName);
 
echo " [*] Waiting for messages. To exit press CTRL+C\n";
 
$callback = function ($msg) {
    echo ' [x] Received ', $msg->body, "\n";
};
 
$channel->basic_consume($queueName, '', false, true, false, false, $callback);
 
while ($channel->is_consuming()) {
    $channel->wait();
}
 
$channel->close();
$connection->close();

  php producter.php

1
 

 

       php customer.php  "exchange_fanout_1"

posted @   setevn  阅读(75)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示