How to post message using rabbit MQ through java

To post a message using RabbitMQ in Java, you can use the RabbitMQ Java client library. 

Here's an example of how to do it: 

 1. Add the RabbitMQ Java client library to your project. 
     You can do this by adding the following dependency to your Maven or Gradle build file:
 Maven:

   <dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>amqp-client</artifactId>
    <version>5.12.0</version>
</dependency>

Gradle
implementation 'com.rabbitmq:amqp-client:5.12.0'

2. Create a connection to the RabbitMQ server:

 3.Create a channel: 

 4. Declare a queue:

 5. Send a message to the queue: 

 6. Close the channel and connection: 

 Putting it all together, here's the complete code to send a message to a RabbitMQ queue using Java:
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

public class MessageSender {
    private final static String QUEUE_NAME = "my_queue";

    public static void main(String[] argv) throws Exception {
        // create a connection to the RabbitMQ server
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();

        // create a channel
        Channel channel = connection.createChannel();

        // declare a queue
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // send a message to the queue
        String message = "Hello, World!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("Sent message: " + message);

        // close the channel and connection
        channel.close();
        connection.close();
    }
}
This code establishes a connection to a RabbitMQ server running on the local machine, declares a queue named "my_queue", and sends a message with the body "Hello, World!" to that queue.

Comments

Popular posts from this blog

What is TensorFlow ? Example with springboot and maven

What are different Power BI components and Architecture

How to connect DynamoDB using AWS and springboot example