Show List

Topic Exchange Demo

Topic exchange is used to route the message to multiple queues using partial matching of the routing key. For this demo, we are first going to create a Topic exchange.

Create Topic Exchange

From RabbitMQ management console, create Topic Exchange.
We will be using Red, Blue, Yellow and Green queues that we created in the previous demo.

Binding Queues to Topic Exchange

Here we are using the wild card character # (hash) to bind the queues. Hash can substitute for zero or more words. So when a message is sent to the exchange it will be sent to the queue if the pattern matches. For example if the message is sent with key red.blue, it will be sent to Red and Blue queues.

Creating Publisher

Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>RabbitMQDemo</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>QPublisher</module>
<module>QConsumer</module>
<module>DirectExchangePublisher</module>
<module>DirectExchangeGreenQConsumer</module>
<module>DirectExchangeYellowQConsumer</module>
<module>DirectExchangeRedQConsumer</module>
<module>TopicExchangePublisher</module>
</modules>

<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.16.0</version>
</dependency>
</dependencies>
</project>
Topic Publisher:
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 TopicPublisher {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

String message = "Hello. Message to queue";
channel.basicPublish("topic-exchange-demo","red.blue",null, message.getBytes());

channel.close();
}
}
When this application is run, the message can be seen on Red and Blue queues:
When we run the Consumer applications are run, messages would get consumed from the queues.

Source code:
https://github.com/it-code-lab/RabbitMQDemo

    Leave a Comment


  • captcha text