Chapter

Your first producer and consumer

Write real RabbitMQ producers and consumers in PHP with php-amqplib: publish and receive messages, share work across workers, acknowledge, and make messages survive a restart.

RabbitMQ Basics 7 Lessons from courses

About this chapter

Time to write code. In this chapter you'll install the PHP client, publish your first message, consume it, and then make the whole thing reliable with work queues, acknowledgements, durability and fair dispatch.

Lessons from courses

  1. 1 Installing the PHP client Install the php-amqplib PHP client with Composer and open your first RabbitMQ connection and channel using AMQPStreamConnection, explained step by step.
  2. 2 Publishing your first message Publish a message with php-amqplib: declare a queue, build an AMQPMessage, and send it to the default exchange with basic_publish, explained line by line.
  3. 3 Consuming messages Consume RabbitMQ messages in PHP with basic_consume and a callback, then keep the consumer alive with a wait loop so it processes messages as they arrive.
  4. 4 Work queues Build a RabbitMQ work queue in PHP: run several competing consumers on one queue and watch round-robin distribution spread tasks across two workers in parallel.
  5. 5 Message acknowledgements Stop losing RabbitMQ messages when a worker crashes. Use manual message acknowledgement: turn off auto-ack, ack after processing, and nack to requeue on failure.
  6. 6 Durability and persistence Make RabbitMQ survive a broker restart in PHP: declare a durable queue, publish persistent messages with delivery_mode 2, and why you need both together.
  7. 7 Fair dispatch and prefetch Stop RabbitMQ overloading one busy worker. Set a prefetch count of 1 with basic_qos for fair dispatch, so slow workers aren't handed more messages, in PHP.
RabbitMQ Basics Go to course