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"
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步