After installing amqp with PHP and try RabbitMQ (amqp extension), you can start to write the code:
Consumer: Receives Messages
Logic:
Create a connection --> create a channel --> Create a switch --> Create a queue --> bind a switch, queue, or route key --> receive a message
'2017. 168.1.93 ', 'port' => '123', 'login' => 'guest', 'password' => 'guest ', 'vhost' => '/'); $ e_name = 'e _ linvo '; // switch name $ q_name = 'Q _ linvo'; // queue name $ k_route = 'key _ 1 '; // route key // create a connection and channel $ conn = new AMQPConnection ($ conn_args); if (! $ Conn-> connect () {die ("Cannot connect to the broker! \ N ") ;}$ channel = new AMQPChannel ($ conn); // Create a vSwitch $ 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 a queue $ q = new AMQPQueue ($ channel); $ q-> setName ($ q_name); $ q-> setFlags (AMQP_DURABLE ); // persistent echo "Message Total :". $ q-> declare (). "\ n"; // Bind the vSwitch and Queue, and specify the route 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); // automatic ACK response} $ conn-> disconnect (); /*** consumption callback function * processes messages */function processMessage ($ envelope, $ queue) {$ msg = $ envelope-> getBody (); echo $ msg. "\ n"; // process the message $ queue-> ack ($ envelope-> getDeliveryTag (); // manually send ACK response}
Producer: send messages
Logic:
Create a connection --> create a channel --> Create a switch object --> Send a Message
'2017. 168.1.93 ', 'port' => '123', 'login' => 'guest', 'password' => 'guest ', 'vhost' => '/'); $ e_name = 'e _ linvo '; // switch name // $ q_name = 'Q _ linvo'; // No queue name required $ k_route = 'key _ 1 '; // route key // create a 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 a vSwitch object $ ex = new AMQPExchange ($ channel); $ ex-> setName ($ e_name ); // send the message // $ channel-> startTransaction (); // start the transaction for ($ I = 0; $ I <5; ++ $ I) {echo "Send Message :". $ ex-> publish ($ message, $ k_route ). "\ n" ;}// $ channel-> commitTransaction (); // submit the transaction $ conn-> disconnect ();
Note the following:
The queue object has two methods for obtaining messages: consume and get.
The former is blocked and will be suspended when there is no message, which is suitable for loop use;
The latter is non-blocking. If no message is received, false is returned.
Test
Running consumer:
Run the producer to send messages:
The consumer receives the message: