php如何使用rabbitmq实现发布消息和消费消息(tp框架)(第一篇)
1,默认已经安装好了rabbitmq: 参考 http://www.cnblogs.com/spicy/p/7017603.html
2,安装rabbitmq客户端: 方法1: pecl 扩展安装 方法2:composer安装
我是用第二种: composer require php-amqplib/php-amqplib
3,新建一个发送的路由 和 接受的路由(tp5)
Route::rule('test','index/index/test1');
Route::rule('getmsg','index/receiver/receive');
4,发布信息的方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php namespace app\index\controller; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; use validator\Validator; class Index { //rbmp example public function test1() { $connection = new AMQPStreamConnection('localhost', 5672, 'bitch', 'bitch'); $channel = $connection->channel(); $channel->queue_declare('hello', false, true); $sendMsg = [ 'name'=>'kevin'.rand(1,100), 'phone'=>'171921743'.rand(1,100), ]; $msg = new AMQPMessage(json_encode($sendMsg)); $channel->basic_publish($msg, '', 'hello'); echo " [x] Sent 'Hello Kevin!'\n"; $channel->close(); $connection->close(); }
5,消费信息的方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php namespace app\index\controller; use PhpAmqpLib\Connection\AMQPStreamConnection; class Receiver { public function receive() { set_time_limit(0); $connection = new AMQPStreamConnection('localhost', 5672, 'bitch', 'bitch'); $channel = $connection->channel(); $channel->queue_declare('hello', false, true); $receiver = new self(); $channel->basic_consume('hello', '', false, true, false, false, [$receiver, 'callFunc']); while(true) { $channel->wait(); } $channel->close(); $connection->close(); } public function callFunc($msg) { $content = json_decode($msg->body,true); //把用户信息插入数据库 db('user_info')->insert([ 'ui_username'=>$content['name'], 'ui_phone'=>$content['phone'], ]); } }
注意: 我们公司是把消费消息做成了常驻