RabbitMQ : Create Dynamic queues in Direct Exchang

2019-07-21 18:42发布

问题:

I am new to RabbitMQ, I just went through Rabbitmq docs (Routing). I am quite confused between Exchange with routing keys. My requirement is , I want to create multiple queues dynamically. Please refer below diagram.

Ex. Lets say If producer create message for consumer c3, then it should go to Exchange and route to Queue 3 only and consume by C3 only. At present I only require 3 Queues in future this count may increase. so how to deal with this situation too.

Note : I refer this blog Exchange

I have used Spring hibernate along with Rabbitmq. below code shows Rabbit MQ Listener configuration File.

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/rabbit  
http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">

<rabbit:connection-factory id="connectionFactory" host="xx.xx.10.181" username="admin" password="admin" />
<rabbit:admin connection-factory="connectionFactory" />

<!--  Create Queues -->
<rabbit:queue id="q1" name="q1.queue" durable="true" />
<rabbit:queue id="q2" name="q2.queue" durable="true"  />
<rabbit:queue id="q3" name="q3.queue" durable="true"  />

<!--create Exchange here -->
<rabbit:direct-exchange id="myExchange" name="MY Exchange">
    <rabbit:bindings>
         <rabbit:binding queue="q1" key="my.queue.q1" />
         <rabbit:binding queue="q2" key="my.queue.q2" />
         <rabbit:binding queue="q3" key="my.queue.q3" />
    </rabbit:bindings>
</rabbit:direct-exchange>

<!-- instantiate Listeners -->
<bean id="q1Listener" class="in.my.brocker.amqp.Q1Listener" />
<bean id="q2Listener" class="in.my.brocker.amqp.Q2Listener" />
<bean id="q3Listener" class="in.my.brocker.amqp.Q3Listener" />

<!-- glue the listener and myAnonymousQueue to the container-->
<rabbit:listener-container id="myListenerContainer" connection-factory="connectionFactory">
    <rabbit:listener ref="q1Listener" queues="q1" />
    <rabbit:listener ref="q2Listener" queues="q2" />
    <rabbit:listener ref="q3Listener" queues="q3" />
 </rabbit:listener-container>
</beans>

In above rabbit-listener-context.xml, I have created 3 Queues along with 3 Listener Classes. My aim is to Queue should be access by defined routing keys. I want to create nth no of queues this dynamically? How can we achieve this?