Implementing Message Producers and Consumers with RabbitMQ

Core concepts in RabbitMQ revolve around three fundamental components: producers that emit messages, consumers that receive them, and queues that store pending messages. A single queue can except messages from multiple producers and deliver them to multiple consumers, acting as a durable buffer limited only by available storage.

Producer Implementation

Below is a Java example that connects to RabbitMQ, declares a queue, and publishes a structured message.

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.fastjson.JSON;

public class MessageSender {
    private static final String TARGET_QUEUE = "RabbitMQ_Hello";

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");

        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            // Ensure the queue exists
            channel.queueDeclare(TARGET_QUEUE, false, false, false, null);

            Map<String, Object> payload = new HashMap<>();
            payload.put("framework", "Spring");
            payload.put("language", "Java");

            String jsonMsg = JSON.toJSONString(payload);
            channel.basicPublish("", TARGET_QUEUE, null, jsonMsg.getBytes());

            System.out.println("Sent: " + jsonMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Consumer Implementasion

The consumer listens on the same queue and processes incoming data in a continuous loop.

import com.rabbitmq.client.*;
import java.io.IOException;

public class MessageReceiver {
    private static final String TARGET_QUEUE = "RabbitMQ_Hello";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(TARGET_QUEUE, false, false, false, null);
        System.out.println("Waiting for messages...");

        DeliverCallback handler = (consumerTag, delivery) -> {
            String content = new String(delivery.getBody(), "UTF-8");
            System.out.println("Received: " + content);
        };

        channel.basicConsume(TARGET_QUEUE, true, handler, consumerTag -> {});
    }
}

After launching the broker locally and running the sender, the message becomes visible in the management dashboard. Executing the receiver consumes it, immediately removing it from the queue.

Tags: RabbitMQ java Message Queue producer Consumer

Posted on Mon, 08 Jun 2026 17:14:00 +0000 by englishman69