Search code examples
spring-rabbit

Declarabes in Spring application using Rabbit MQ


I am using spring aqmp version 2.2.6 to create multiple binding to a topic exchange. I understand from the discussion and the reference document that i can use declarables .Spring AMQP: Creating multiple queues dynamically

But in my case i will have the routing keys in the application config as comma seperated and ever growing . How would i use the config to create the declarable bean dynamically. ? below is application config entry. rabbit.MQ_SUBSCRIBER_ROUTING_KEY = my.#,test.#

The routing key will be added as in when required by service .

Shoud i loop the rabbit.MQ_SUBSCRIBER_ROUTING_KEY and call bean function ?


Solution

  • my.queues=foo,bar,baz
    

    Spring can convert that to a List<String>.

    @Bean
    public Declarables queues(@Value("${my.queues}") List<String> queues) {
        return new Declarables(queues
                .stream()
                .map(q -> new Queue(q))
                .collect(Collectors.toList())
                .toArray(new Queue[0]));
    }
    

    EDIT

    For the complete picture:

    @Bean
    public Declarables declarables(@Value("${my.queues}") List<String> queues,
            @Value("${my.exchange}") String exch, 
            @Value("${my.routing.keys}") List<String> routingKeys) {
    
        List<Declarable> declarables = queues
                        .stream()
                        .map(q -> new Queue(q))
                        .collect(Collectors.toList());
        declarables.add(new DirectExchange(exch));
        for (int i = 0; i < routingKeys.size(); i++) {
            declarables.add(new Binding(queues.get(i), DestinationType.QUEUE, exch, 
                    routingKeys.get(i), null));
        }
        return new Declarables(declarables
                .toArray(new Declarable[0]));
    }
    
    my.queues=foo,bar,baz
    my.exchange=qux
    my.routing.keys=rk1,rk2,rk3