What is Queue in RabbitMQ? What are its characteristics?

What is Queue in RabbitMQ? What are its characteristics?

The Queue in RabbitMQ is a message buffer used to store pending messages. It is the most basic messaging model in RabbitMQ. Queue has the following characteristics:

  1. A queue is a container for messages: the queue is used to store messages to be processed, and messages are processed in first-in, first-out (FIFO) order.

  2. The queue is bounded: the queue has a maximum capacity limit. When the queue is full, new messages will not be able to enter the queue until the messages in the queue are consumed or manually deleted.

  3. Queues are persistent: messages in the queue can be persisted to disk to prevent message loss. When the RabbitMQ server is restarted, persisted messages will be restored.

  4. Queues are configurable: Queues can be configured by setting different properties, such as the name of the queue, whether it is persistent, whether it is automatically deleted, etc.

Here is a code example written in Java that demonstrates how to declare a queue and send messages:

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class QueueExample {
    
    

    private final static String QUEUE_NAME = "my_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
    
    
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        // 创建连接
        Connection connection = factory.newConnection();

        // 创建通道
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);

        // 发送消息
        String message = "Hello, RabbitMQ!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("Sent message: " + message);

        // 关闭通道和连接
        channel.close();
        connection.close();
    }
}

In the above code, first we create a connection factory and set the host address of the RabbitMQ server. We then created a connection using a connection factory and a channel using the connection. Next, we queueDeclaredeclare a queue named "my_queue" using the method. In queueDeclarethe method, we can set various properties of the queue, such as whether it is persistent, whether it is automatically deleted, etc. When sending a message, we use basicPublisha method to send the message to the queue.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/132892114