Try Rabbitmq with PHP (AMQP extension)

Source: Internet
Author: User
Tags ack log log switches rabbitmq

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

<?php/************************************* * php amqp (RabbitMQ) demo-consumer * AUTHOR:LINVO * DATE:2012/7/30 * ///configuration information $conn _args = array (' host ' = ' 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

<?php/************************************* * php  AMQP (RabbitMQ) demo-publisher * author:linvo * DATE:2012/7/30 *************************************///configuration information $conn _args = Array (' host ' = ' 192.168.1.93 ', ' port ' = ' 5672 ', ' login ' = ' guest ', ' password ' = ' + ' gu   Est ', ' 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:



Application of RABBITMQ message queue under PHP

In the implementation of Message Queuing, RABBITMQ is known for its robustness and reliability. The company's project has chosen it as the implementation of Message Queuing. About the mechanism and principle of MQ there are many articles on the web that you can see here, and we'll just talk about a few more confusing questions.

1,binding Key and Routing key

The binding key and the routing key are all just the set of characters that you are setting, except that the binding key is a string that is passed through the method when the switch and queue are bound, and routing key is the string that is brought in when the message is posted, Some people say that these two are actually a thing, is also not right, say yes, because the two can be exactly the same, said wrong, because the role of these two different, a switch can bind a lot of queues, but each queue may require different message types, binding A key is the message that is left between the switch and the queue when the message is sent, and the routing key that is sent along with the message, if it is the same as the binding key, indicates that the message is what this queue wants, and if it is not, do not give this queue, Switch you look for the next queue to see if you want to. Understand, these two keys is the password, on the right is their own people, not on that trouble you find again.

The pairing of the binding key and the routing key is not exactly the same, it can be ' similar ' pairing, when the switch is set up, it is time to tell MQ that I want to declare that the switch and the queue above it require routing key and binding to transmit the message. Key exactly the same, this mode is called direct, if the routing key and the binding key can be ' fuzzy ' match, this mode is called topic, if not need to match, despite the hair, called fanout.

2, persistent

Both the switch and the queue can be set to persistent at the time of creation, the reboot will reply later, but the message is not, if the message is also restored, when the message is published to the switch, you can specify a flag "Delivery mode" (drop pattern), 1 is non-persistent, 2 is persistent.

3, flow control mechanism

  when the message is produced faster, and the process is low-processing, the message accumulates, consumes more memory and causes MQ to crash, so RABBITMQ has a flow control mechanism that stops receiving messages when the limit is exceeded, and MQ flow control has three mechanisms


1, actively block the message too fast connection, this cannot be adjusted, if blocked, on the Abbitmqctl console will show a blocked status. 2, memory exceeds limit, will block connection, adjustable in Vm_memory_high_watermark 3, the remaining disk is limited to the following MQ will actively block all producers, the default is 50m, Disk_free_limit adjustable.The following is the MQ installation process above the CENTOS7.

  

1, the necessary support

Yum install ncurses-devel   UnixODBC unixodbc-devel  

2,erlang Environment

wget Http://www.erlang.org/download/otp_src_17.3.tar.gztar zxvf otp_src_17.3.tar.gzcd otp_src_17.3./configure-- without-javac# Ignore warnings make && make install

3, install RABBITMQ dependent files, install RABBITMQ

Yum Install Xmltowget Http://www.rabbitmq.com/releases/rabbitmq-server/v3.4.1/rabbitmq-server-3.4.1.tar.gztar ZXVF RABBITMQ-SERVER-3.4.1.TAR.GZCD rabbitmq-server-3.4.1/make TARGET_DIR=/USR/RABBITMQ SBIN_DIR=/usr/rabbitmq/sbin Man _dir=/usr/rabbitmq/man Doc_install_dir=/usr/rabbitmq/docmake TARGET_DIR=/USR/RABBITMQ SBIN_DIR=/usr/rabbitmq/sbin Man_dir=/usr/rabbitmq/man Doc_install_dir=/usr/rabbitmq/doc  Install/usr/rabbitmq/sbin/rabbitmq-server- Detached start Rabbitmq/usr/rabbitmq/sbin/rabbitmqctl Status View status/usr/rabbitmq/sbin/rabbitmqctl stop Close RABBITMQ

4. Enable the management plug-in

MKDIR/ETC/RABBITMQCD  /usr/rabbitmq/sbin./rabbitmq-plugins Enable rabbitmq_management  (plug-in enabled). Rabbitmq-plugins Disable rabbitmq_management (disable plugin) # Restart rabbitmq# Access http://127.0.0.1:15672/# If there is iptables# vi/etc/ Sysconfig/iptables  Add #    -A input-m State--state new-m tcp-p TCP--dport 15672-j accept# restart iptable systemc   TL Restart Iptables.service

5. Create a configuration file

#在/usr/rabbitmq/sbin/rabbitmq-defaults View config file path # Create profile Touch/usr/rabbitmq/sbin#vm_memory_high_watermark Memory low watermark, if lower than the watermark, turn on the flow control mechanism, block all requests, the default value is 0.4, that is, the total amount of memory 40%, #vm_memory_high_watermark_paging_ratio The percentage of memory low watermark starts by writing to the disk file to free up memory vi/usr/rabbitmq/sbin/rabbitmq.config input [{rabbit, [{vm_memory_high_watermark_paging_ Ratio, 0.75},         {Vm_memory_high_watermark, 0.7}]}].

6. Create an environment file

touch/etc/rabbitmq/rabbitmq-env.conf# Enter    rabbitmq_nodename=fztec-240088 node name    rabbitmq_node_ip_address= 127.0.0.1 monitoring IP    rabbitmq_node_port=5672 listening port    rabbitmq_log_base=/data/rabbitmq/log log directory    rabbitmq_ Plugins_dir=/data/rabbitmq/plugins plug-in directory    Rabbitmq_mnesia_base=/data/rabbitmq/mnesia back-End Storage directory

7, install PHP RABBITMQ extension

Yum install librabbitmq-devel.x86_64wget Http://pecl.php.net/get/amqp-1.4.0.tgztar zxvf amqp-1.4.0.tgzcd amqp-1.4.0/ Usr/local/php/bin/phpize./configure--with-php-config=/usr/local/php/bin/php-config--with-amqpmake && Make install    vim/usr/local/php/etc/php.ini# input          extension=amqp.soservice nginx reloadservice php-fpm Restart

Action commands

View exchange information          /usr/rabbitmq/sbin/rabbitmqctl list_exchanges name type durable auto_delete arguments view queue information          / USR/RABBITMQ/SBIN/RABBITMQCTL list_queues Name Durable auto_delete messages Consumers me  View binding information          /USR/RABBITMQ /sbin/rabbitmqctl list_bindings View connection information          /usr/rabbitmq/sbin/rabbitmqctl list_connections

Server-side scripting for PHP

<?php$routingkey= ' key ';//Set your connection $conn_args = Array (' host ' = = ' localhost ', ' port ' = ' 5672 ', ' login ' = ' guest ' ', ' password ' = ' guest '), $conn = new Amqpconnection ($conn _args), if ($conn->connect ()) {echo "established a conn Ection to the broker \ n ";} else {echo "Cannot connect to the broker \ n";} Your message $message = Json_encode (Array (' Hello world3! ', ' php3 ', ' c++3: '));//Create Channel$channel = new Amqpchannel ($conn);// Create Exchange$ex = new Amqpexchange ($channel); $ex->setname (' Exchange ');//Create name $ex->settype (amqp_ex_type_direct) ; $ex->setflags (amqp_durable);//$ex->setflags (amqp_autodelete);//echo "Exchange Status:" $ex->declare ();                echo "Exchange Status:". $ex->declareexchange (); echo "\ n"; for ($i =0; $i <100; $i + +) {if ($routingkey = = ' Key2 ') {        $routingkey = ' key ';        }else{$routingkey = ' Key2 '; } $ex->publish ($message, $routingkey);} /* $ex->publish ($message, $routingkey); Create queue $q = new Amqpqueue ($channel); Set queue name if it does not existAdd $q->setname (' queue '); $q->setflags (amqp_durable | Amqp_autodelete); echo "Queue status:". $q->declare (); echo "\ n"; Echo ' queue bind: '. $q->bind (' Exchange ', ' Route.key '); bind your queue to Routingkeyecho "\ n"; $channel->starttransaction (); echo "Send:". $ex->publish ($message, ' Route.key '); Send your message by making Routingkey $channel->committransaction (); $conn->disconnect (); * *

PHP Client Script

<?php$bindingkey= ' key2 ';//connection Rabbitmq$conn_args = Array (' host ' = ' 127.0.0.1 ', ' port ' = ' 5672 ', ' login ' = ' = ') Guest ', ' password ' = ' guest ', ' vhost ' = '/'); $conn = new Amqpconnection ($conn _args); $conn->connect ();// Set the queue name, use Exchange, bind Routingkey$channel = new Amqpchannel ($conn), $q = new Amqpqueue ($channel); $q->setname (' Queue2 '); $q->setflags (amqp_durable); $q->declare (); $q->bind (' Exchange ', $bindingkey);//Message Get $messages = $ Q->get (Amqp_autoack), if ($messages) {var_dump (Json_decode ($messages->getbody (), True));} $conn->disconnect ();? >

Translation of some MQ constant settings, incorrect place, everyone to test

/** * Passing in this constant as a flag would forcefully disable all other flags. * Use this if you want to temporarily disable the Amqp.auto_ack INI setting. * Pass this parameter as flag will completely disable other flags if you want to temporarily disable Amqp.auto_ack setting */define (' Amqp_noparam ', 0);/** * Durable exchanges and queues would Survive a broker restart, complete with all of their data.  * Persistent switches and queues that persist after the agent restarts and include the full data in them */define (' amqp_durable ', 2);/** * Passive Exchanges and queues will is not redeclared, But the broker would throw a error if the Exchange or queue does not exist. * Passive mode switches and queues cannot be redefined, but if the switch and queue do not exist, the agent throws an error message */define (' Amqp_passive ', 4);/** * Valid for queues only, this flag indicat Es that is only one client can is listening to and consuming from the this queue. * Only valid for queues, this person flag defines the queue to allow only one client to connect and consume messages from it */define (' amqp_exclusive ', 8);/** * For exchanges, the auto delete flag indicates tha t the exchange would be a deleted as soon as no more queues is bound * to it. If no queues were ever bound the exchange, the exchange would never be DelEted. For queues, the auto Delete * flag indicates that the queue would be deleted as soon as there is no more listeners SUBSCRI Bed to it. If no * Subscription has ever been active, the queue would never be deleted. Note:exclusive queues would always is * automatically deleted with the client disconnects. * For the switch, the auto-delete flag indicates that the switch will be automatically deleted without a queue binding, and the switch will not be deleted if there is no queue and it is bound. * For the queue, the auto-delete flag means that if no consumer and you bind the words will be automatically deleted, if there is no consumer and its binding, will not be deleted, the exclusive queue will always be deleted when the customer is disconnected */define (' amqp_autodelete ', 16);/** * Clients is not allowed to make specific queue bindings to exchanges defined with the this flag.  * This flag identifies a custom queue that is not allowed to bind to the switch on */define (' amqp_internal ', +);/** * When passed to the consume method for a clustered environment, Do not consume from the local node. * This parameter is passed in the cluster environment consumption method, indicating that the message will not be consumed from the local site (' amqp_nolocal ', */define);/** * When passed to the {@link amqpqueue::get ()} and {@lin K Amqpqueue::get ()} methods as a flag, * the messages would be immediately marked as acknowledged by the server upon delive Ry. * When in the queue get methodWhen this parameter is passed as a flag, the message will be marked as acknowledged (received) before being output by the server */define (' amqp_autoack ', +);/** * Passed on the queue creation, this flag I Ndicates that the queue should is deleted if it becomes empty. * This parameter is passed when the queue is established, indicating that the queue will be deleted when it is empty (' Amqp_ifempty ', */define);/** * Passed on the queue or exchange creation, this flag ind Icates that the queue or exchange should is * deleted when no clients is connected to the given queue or exchange. * Pass this parameter when the switch or queue is established, this flag indicates that when there is no client connection, the switch or queue will be deleted */define (' amqp_ifunused ');/** * When publishing a message, the Message must is routed to a valid queue. If It isn't, an error would be returned. * When publishing a message, the message must be properly routed to a valid queue, otherwise an error */define (' Amqp_mandatory ', 1024x768) will be returned;/** * When publishing a message, Mark this MESSAG E for immediate processing by the broker. (High-priority message.) * This message will be processed immediately when the message is posted. */define (' amqp_immediate ', 2048);/** * If set during a call to {@link amqpqueue::ack ()}, the delivery tag is treated as "u p to and including ', so that multiple * MessaGES can is acknowledged with a single method. If set to zero, the delivery tag refers to a single message. * If The AMQP_MULTIPLE flag is set, and the delivery tag are zero, this indicates acknowledgement of all outstanding * mess Ages. * When this flag is set when calling Amqpqueue::ack, the pass label will be treated as a maximum containing quantity so that multiple messages are marked as received by a single method, if set to 0 * The pass label points to a single message, if Amqp_multiple is set and the pass label is 0,  Mark all outstanding messages as received */define (' amqp_multiple ', 4096);/** * If set during a call to {@link amqpexchange::bind ()}, the server will Not respond to the method. The client should not wait * for a reply method. If the server could not complete the method it would raise a channel or connection exception. * When calling the Amqpexchange::bind () method, the server will not respond to the request, the client should not wait for the response, and if the server cannot complete the method, an exception will be thrown */define (' amqp_nowait ', 8192);/** * IF Set during a call to {@link amqpqueue::nack ()}, the message would be placed back to the queue. * If set when the Amqpqueue::nack method is called, the message will be passed back to the queue */define (' Amqp_requeue ', 16384);/** * A Direct exchange type. * DIRECT type Switch */define (' amqp_ex_type_direct ', ' DirecT ');/** * A fanout exchange type. * fanout type Switch */define (' amqp_ex_type_fanout ', ' fanout ');/** * A topic Exchange type. * TOPIC type Switch */define (' amqp_ex_type_topic ', ' TOPIC ');/** * A header exchange type. * Header type Switch */define (' amqp_ex_type_headers ', ' HEADERS ');/** * SOCKET Connection Timeout setting */define (' Amqp_os_socket_timeout_errno ') , 536870947);

Try Rabbitmq (amqp extension) with PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.