Once you've installed AMQP, you're ready to start writing code:
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 _name = ' 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 broker!\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 "; The blocking mode receives the 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
' 192.168.1.93 ', ' port ' = ' 5672 ', ' login ' = ' guest ', ' password ' and ' 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 broker!\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: