Search code examples
javaspringspring-bootspring-integrationspring-integration-amqp

How to dynamically add queue to exchange in Spring Integration


I have the following exchange in integrationcontext.xml

<!-- rabbit exchanges, queues, and bindings used by this app -->
<rabbit:topic-exchange name="newPaymentEventsExchange" auto-delete="false" durable="true">
    <rabbit:bindings>

    </rabbit:bindings>
</rabbit:topic-exchange>

I need to be able to dynamically add queues to the exchange based on values of channelName from the following object from the database, also I should be able to update when someone adds a new channel:

public class Channel {
    private Long channelId;
    private String tenantId;
    private String channelName;

    ------
    //Getters & setters
 }

Solution

  • Use AmqpAdmin to perform this kind of operations:

    /**
     * Declare the given queue.
     * @param queue the queue to declare.
     * @return the name of the queue.
     */
    String declareQueue(Queue queue);
    
    /**
     * Declare a binding of a queue to an exchange.
     * @param binding a description of the binding to declare.
     */
    void declareBinding(Binding binding);
    

    You may consider to use QueueBuilder and BindingBuilder for convenience:

    QueueBuilder.nonDurable("foo")
        .autoDelete()
        .exclusive()
        .withArgument("foo", "bar")
        .build()
    ...
    BindingBuilder.bind(
                marketDataQueue()).to(marketDataExchange()).with(marketDataRoutingKey)
    

    https://docs.spring.io/spring-amqp/docs/2.0.0.RELEASE/reference/html/_reference.html#broker-configuration