Use PHP to try Rabbitmq (AMQP extensions) to send and receive messages
Consumer: Receiving Messages
Logic:
Create a connection--create a channel--> switch--Create a queue--bind switch/queue/route keys receive Message
' 192.168.1.93 ', ' port ' = ' 5672 ', ' login ' = ' guest ', ' Password ' + ' guest ', ' vhost ' = '/'); $e _nam E = ' e_linvo '; Switch name $q_name = ' Q_linvo '; Queue name $k_route = ' Key_1 '; Route key//Create connection and channel$conn = new Amqpconnection ($conn _args), if (! $conn->connect ()) {die ("Cannot connect to the Brok Er!\n ");} $channel = new Amqpchannel ($conn);//create switch $ex = new Amqpexchange ($channel); $ex->setname ($e _name); $ex->settype ( Amqp_ex_type_direct); Direct type $ex->setflags (amqp_durable); Persistent echo "Exchange Status:" $ex->declare (). " \ n ";//Create queue $q = new Amqpqueue ($channel); $q->setname ($q _name); $q->setflags (amqp_durable); Persistent echo "Message total:". $q->declare (). " \ n ";//Bind the switch with the queue and specify the routing key Echo ' queue Bind: '. $q->bind ($e _name, $k _route)." \ n ";///block mode Receive message echo" message:\n ", while (True) {$q->consume (' ProcessMessage '); $q->consume (' ProcessMessage ', amqp_autoack); Auto ack reply} $conn->disconnect ();/*** consumption callback function * Processing message */function ProcessMessage ($envelope, $queue) {$msg = $envelope->getbody (); echo $msg. " \ n "; Processing Messages $queue->ack ($envelope->getdeliverytag ()); Send ACK reply manually}
Producer: Send Message
Logic:
Create a connection--create a channel--> switch Object--Send a message
!--? php/************************************** php amqp (RabbitMQ) Demo- publisher* author:linvo* date:2012/7/30*************************************///configuration information $conn_args = Array (' Host ' =--> ' 1 92.168.1.93 ', ' port ' = ' 5672 ', ' login ' = ' guest ', ' password ' = ' guest ', ' vhost ' + '/'); $e _name = ' E_linvo '; Switch name//$q _name = ' q_linvo '; No queue name $k_route = ' Key_1 '; Route key//Create connection and channel$conn = new Amqpconnection ($conn _args), if (! $conn->connect ()) {die ("Cannot connect to the Brok Er!\n ");} $channel = new Amqpchannel ($conn);//message content $message = "TEST message! Test Message! ";//Create switch Object $ex = new Amqpexchange ($channel); $ex->setname ($e _name);//Send Message//$channel->starttransaction (); Start transaction for ($i =0; $i <5; + + $i) {echo "Send Message:". $ex->publish ($message, $k _route). " \ n ";} $channel->committransaction (); Commit Transaction $conn->disconnect ();
The areas to note are:
The queue object has two methods available for fetching messages: consume and get.
The former is blocked, no message will be suspended, suitable for use in the loop;
The latter is non-blocking, when the message is taken, and none returns false.
Test
Run the consumer:
Run producer, send message:
The consumer receives the message:
?
Http://nonfu.me/p/9722.html