How To Send Messages In RabbitMQ

dimitrilc 1 Tallied Votes 550 Views Share

Introduction

In the last tutorial, we learned how to set up our own RabbitMQ exchanges and queues. In this tutorial, we will learn how to send messages to our custom daniweb-exchange.

Goals

At the end of the tutorial, you would have learned:

  1. How to send messages in RabbitMQ.

Tools Required

  1. A RabbitMQ server with the same custom exchange and queue from this tutorial.

Prerequisite Knowledge

  1. RabbitMQ Exchanges and Queues.
  2. Basic Java (only second part).

Project Setup

To follow along with the tutorial, perform the steps below:

  1. Log into RabbitMQ’s management interface.

Send Message Using The Management Interface

The most convenient method to send a message is via the management interface itself. Keep in mind that this is only possible to users who have permission to access the management interface.

To send a message to the daniweb-exchange, follow the steps below.

  1. Go to Exchanges, and then select daniweb-exchange.
    Screen_Shot_2022-09-08_at_5.47.55_PM.png

  2. Scroll down until you see Publish Message. Fill in the information exactly like the screenshot below. The Routing key and the Properties must be valid. Payload and Headers can be set with your value of choice.
    Screen_Shot_2022-09-08_at_5.50.53_PM.png

  3. Hit Publish message.

Because we used the routing key daniweb-to-my-queue, the message is automatically sent to my-queue. If we switched back to the my-queue view, then we can see the message that we just sent in the ready status.

Screen_Shot_2022-09-08_at_6.03.04_PM.png

This message will stay in the queue until it is consumed and acked.

Creating A New User

The admin user that we have been using is fine for tasks that can be done on the management interface, but for sending or receiving messages from outside the management interface, it is probably better to create a different user. To create a new user, follow the steps below.

  1. Select the Admin tab.
  2. On the right-hand-side navigation bar, select Users.
  3. Expand Add a user.
  4. Set the username to sender.
  5. Sett the password to password.
  6. Hit Add user.

Screen_Shot_2022-09-08_at_4.59.12_PM.png

After the user sender is created, the management interface will show that this user has no access to any virtual host.

Screen_Shot_2022-09-08_at_5.05.35_PM.png

In RabbitMQ, virtual hosts are used to isolate exchanges, queues, authorization (authentication is still shared among all virtual hosts) and many more properties. This feature is useful when you are running a multi-tenant setup.

For example, if you own a paid weather data streaming service and charges your clients to access this data, then it probably makes more sense to have two different clients, Weather Channel and AccuWeather, on different virtual hosts, so each client can have their own queues and exchanges.

Because our project system is simple, we are only going to be concerned about the default virtual host slash (/). In order to send messages, then the sender user would need the write permission to a virtual host /.

  1. Click on the Name sender to go into its configuration.
  2. Leave Configure regex and Read regex blank.
  3. The Write regex needs to have .* as the value.
  4. Finally, hit Set permission.

Screen_Shot_2022-09-08_at_5.29.07_PM.png

We can now see that the use has permission to send messages to the virtual host /.

Screen_Shot_2022-09-08_at_5.36.51_PM.png

Send Message In Code

A more normal method of sending messages with a program. Follow the steps below to create a small Java program.

  1. Create a new text file called PublishSample.java under the ~/Downloads directory for your system.

  2. Copy and paste the code below into the file.

     import com.rabbitmq.client.AMQP;
     import com.rabbitmq.client.ConnectionFactory;
    
     import java.io.IOException;
     import java.nio.charset.StandardCharsets;
     import java.util.concurrent.TimeoutException;
    
     public class PublishSample {
        private static final String USERNAME = "sender";
        private static final String PASSWORD = "password";
        private static final String ROUTING_KEY = "daniweb-to-my-queue";
        private static final String EXCHANGE_NAME = "daniweb-exchange";
        private static final String BODY = "Hello World From Java!";
    
        public static void main(String... args){
            var factory = new ConnectionFactory();
            factory.setUsername(USERNAME);
            factory.setPassword(PASSWORD);
            factory.setHost(ConnectionFactory.DEFAULT_HOST);
            factory.setVirtualHost(ConnectionFactory.DEFAULT_VHOST);
            factory.setPort(ConnectionFactory.DEFAULT_AMQP_PORT);
    
            try(var conn = factory.newConnection();
                var channel = conn.createChannel()){
                var props = new AMQP.BasicProperties.Builder()
                        .deliveryMode(1)
                        .build();
                channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, props, BODY.getBytes(StandardCharsets.UTF_8));
            } catch (IOException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
     }
  3. Download the amqp-client-5.15.0.jar from https://www.rabbitmq.com/java-client.html.

  4. Download the slf4j-simple-2.0.0.jar from https://repo1.maven.org/maven2/org/slf4j/slf4j-simple/2.0.0/.

  5. Download the slf4j-api-2.0.0.jar from https://repo1.maven.org/maven2/org/slf4j/slf4j-api/2.0.0/.

  6. Place all three jars under the ~/Downloads directory in your system.

  7. In your terminal, execute the program using the command java -cp "Downloads/*" Downloads/PublishSample.java. You might need to modify the directories in the command, depending on your current working directory or operating system.

After the command is executed, then you can see another message in the RabbitMQ management system (two messages in total).

Screen_Shot_2022-09-08_at_10.44.26_PM.png

Summary

You have learned how to send messages using two different ways in RabbitMQ, as well as how to create a new user. In the next tutorial, we will learn how to consume these messages.