Publishing is also quite simple: we can immediately specify the message text, the content type contained in the message, and delivery_mode, which determines how quickly the message appears in the queue.
We call basic_publish, and everything is sent to the queue immediately.
Then we can retrieve something from the queue.
For this we use basic_get, specify which queue we are reading from, and specify the message. This message also stores, in addition to our message and the data we set, information about which channel was used and which one is currently used, which routing_key was used, and generally everything that surrounded our message during processing.
Next, we use basic_ack (acknowledge),
That is, we specify the basic locking mechanism, receive a test message (in our case, body), and can inspect it.
Now let's talk about consume: it is a connection to a queue with the expectation that messages will arrive there. In principle, we could use basic_get, wrap it in a loop, and simply wait for a message from the queue.
But there may be nothing in the queue, and in addition we will be taking an inefficient path.
That is why consume was created: it is a long-lived connection through which you can receive things.
The first parameter is the queue
Next: consumer_tag is the consumer identifier; nowait means do not wait for a server response, i.e. continue consuming; callback is the PHP function that will be called when a message is received.
This results in a somewhat asynchronous working model.
Since we are calling process_message and specifying a callback function, we need to define and name that function.
It is not very complex: a message arrives, and we can do something with it.
We can also exit this loop, that is, pause consume from inside the callback.
To do this, as shown in the example, we need to check the body.
If quit comes in the body, as in the example, we need to exit.
To exit, we go back through message to the channel object stored in the message property, and call basic_cancel with some tag. Consumer_tag shows who took this message for processing. So we exit, and our loop stops and ends.
We will still need a while loop, but the consume approach is more optimal than constantly requesting messages, because a new connection is not created for every request.
Here register_shutdown_function is a standard PHP function in which we can define a callback function, for example shutdown, that will run when the script finishes.
When a script finishes, it is always better to close connections
As a result of these actions, we add a text message to the queue, basic_cancel is called, and the channels and connections are closed. Delivery stores additional information about how the message was processed.
If you need to send many messages at once, it is better to use publish_batch, which creates a transaction from multiple messages. It is very simple.