RabbitMQ + PHP (3) case study and rabbitmq demonstration
Today, we use a simple case to implement the Message Queue running mechanism of RabbitMQ + PHP.
There are two main parts:
1. publisher)
Second: consumer)
(1) Producer (create a rabbit_publisher.php file)
Create a connection --> Create a channel --> Create a switch object --> send a message
$ Conn_args = array ('host' => '127. 0.0.1 ', 'Port' => '123456', 'login' => 'guest', 'Password' => 'guest ', 'vhost' => '/'); // 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 $ e_name = 'e _ linvo '; // switch name $ 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"; echo "Send Message :". $ ex-> publish ("test message, key_1 by Songtao ". date ('H: I: s', time (), 'key _ 1 '). "\ n"; echo "Send Message :". $ ex-> publish ("test message, key_2 by Songtao ". date ('H: I: s', time (), 'key _ 2 '). "\ n ";
(2) Consumer (create a rabbit_consumer.php file)
Create a connection --> Create a channel --> Create a switch --> Create a queue --> bind a switch, queue, or route key --> receive a message
$ Conn_args = array ('host' => '127. 0.0.1 ', 'Port' => '123456', 'login' => 'guest', 'Password' => 'guest ', 'vhost' => '/'); $ e_name = 'e _ linvo '; // switch name $ q_name = 'q _ linvo'; // queue name $ k_route = 'key _ 2 '; // 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 // Bind the vswitch and Queue, and specify the route key echo 'queue Bind :'. $ q-> bind ($ e_name, 'key _ 2 '). "\ n"; // echo "Message: \ n" in blocking mode; $ q-> consume ('processmessage', AMQP_AUTOACK ); // automatic ACK response $ conn-> disconnect ();/*** consumption callback function * processes the message */function processMessage ($ envelope, $ queue) {var_dump ($ envelope-> getRoutingKey); $ msg = $ envelope-> getBody (); echo $ msg. "\ n"; // process the message}
Run two files and then open the Management Center http: // 127.0.0.1: 15672/of RabbitMQ/
It indicates that your program runs normally.
If something is wrong, Hope, criticize and correct it! Thank you.