To send various types of messages with diverse routing keys in Java using the RabbitMQ messaging system, the following steps can be followed:
Create a connection to the RabbitMQ server using the ConnectionFactory class.
Create a channel object using the connection object.
Declare the exchange to be used for sending messages using the exchangeDeclare() method. The exchange can be of type direct, topic, fanout or headers.
Declare the queue(s) to be used for receiving messages using the queueDeclare() method. If the queue is not already created, RabbitMQ will create it when the first message is sent.
Bind the queue(s) to the exchange using queueBind() method with the relevant routing key.
Create the message object using the BasicProperties class and set the routing key and message body.
Publish the message using the basicPublish() method with the exchange name and the message object.
Close the channel and connection objects.
Example code for sending message with different routing key using Java:
import com.rabbitmq.client.*;
public class SendMessage {
private static final String EXCHANGE_NAME = "my_exchange";
private static final String ROUTING_KEY1 = "key1";
private static final String ROUTING_KEY2 = "key2";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
// Declare the exchange
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
// Declare the queues
channel.queueDeclare("queue1", false, false, false, null);
channel.queueDeclare("queue2", false, false, false, null);
// Bind the queues to the exchange with their respective routing keys
channel.queueBind("queue1", EXCHANGE_NAME, ROUTING_KEY1);
channel.queueBind("queue2", EXCHANGE_NAME, ROUTING_KEY2);
//Create and send message with routing key 1
String message1 = "Message 1";
BasicProperties props1 = new BasicProperties.Builder().routingKey(ROUTING_KEY1).build();
channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY1, props1, message1.getBytes("UTF-8"));
//Create and send message with routing key 2
String message2 = "Message 2";
BasicProperties props2 = new BasicProperties.Builder().routingKey(ROUTING_KEY2).build();
channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY2, props2, message2.getBytes("UTF-8"));
}
}
}
Asked: 2021-06-17 11:00:00 +0000
Seen: 8 times
Last updated: May 29 '22