RabbitMQ is a great option for the implementation of an AMQP (Advanced Message Queuing Protocol) queuing system.
Why would you need a queuing system? So that you can offload heavy tasks to be processed in a separate process asynchronously and avoid blocking your client, on your website for instance.
Examples of use cases are (but not limited to):
So why this article? Well the great getting started articles at RabbitMQ are really straight forward but some of the set up is not done for you. This setup/article configures the php containers with the right modules and enables them so that the AMQP library can run from PHP.
As I like to dockerise everything here is my set up ready for you to checkout and run on your machine.
The receivers/workers are randomly delayed so you can see a few messages piling up in the queue. A sample output from the docker logs is
php_receiver_4 | [x] Host: 3160348a0f9f Waiting: 26 seconds. Received msg: Hello World!
rabbitmq_1 | 2018-02-19 21:45:54.389 [info] <0.10243.0> closing AMQP connection <0.10243.0> (172.20.0.8:33396 -> 172.20.0.3:5672, vhost: ‘/’, user: ‘guest’)
rabbitmq_1 | 2018-02-19 21:45:54.543 [info] <0.10256.0> accepting AMQP connection <0.10256.0> (172.20.0.8:33398 -> 172.20.0.3:5672)
rabbitmq_1 | 2018-02-19 21:45:54.549 [info] <0.10256.0> connection <0.10256.0> (172.20.0.8:33398 -> 172.20.0.3:5672): user ‘guest’ authenticated and granted access to vhost ‘/’
rabbitmq_1 | 2018-02-19 21:45:54.588 [warning] <0.10256.0> closing AMQP connection <0.10256.0> (172.20.0.8:33398 -> 172.20.0.3:5672, vhost: ‘/’, user: ‘guest’):
rabbitmq_1 | client unexpectedly closed TCP connection
php_receiver_1 | [x] Done
php_receiver_4 | [x] Done
The receive.php core part is implemented in these lines https://github.com/bizmate/getting-started-rabbitmq-php-dockerised/blob/master/src/receive.php#L19-L26 and as you can see it waits for a random number of seconds before echoing the message received by the send.php/queue.
Thats all folks!
I hope you find this article useful.
If you are looking for a PHP/DevOps/Docker consultant feel free to drop me a message from the contact us link.