Skip to content
Advertisement

How to create dynamic queues in rabbit mq using spring boot?

I need some help.

I’m developing a spring boot application, and I want wo publish messages to a rabbitMQ. I want to send it to a queue, that is named in the message itself. This way i want to create queues dynamicly. I only found examples that use a “static” queue.

I have reserched some things but didn’t find anything. I’m new to RabbitMQ and learned the basic concepts. I’m also fairly new to spring.

RabbotMQ Config

@Configuration
public class RabbitMQConfig {

    @Value("amq.direct")
    String exchange;

    @Value("queue-name") // Don't want to do this
    String queueName;

    @Value("routing-key") // Or this
    String routingkey;

    @Bean
    Queue queue() {
        return new Queue(queueName, true);
    }

    @Bean
    DirectExchange exchange() {
        return new DirectExchange(exchange);
    }

    @Bean
    Binding binding(Queue queue, DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(routingkey);
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpTemplate template(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
}

MessageSender

@Service
public class RabbitMQSender {

    @Autowired
    private AmqpTemplate template;

    @Value("amq.direct")
    private String exchange;

    public void send(MessageDTO message) {
        template.convertAndSend(exchange, message);

    }
}

Advertisement

Answer

I came to a solution:

You need to create a AmqpAdmin in your config:

@Bean
public AmqpAdmin amqpAdmin() {
    return new RabbitAdmin(connectionFactory);
}

Then you add it to your service:

@Autowired
private AmqpAdmin admin;

Finally you can use it to create queues and bindings.

Queue queue = new Queue(queueName, durable, false, false);
Binding binding = new Binding(queueName, Binding.DestinationType.QUEUE, EXCHANGE, routingKey, null);
admin.declareQueue(queue);
admin.declareBinding(binding);

I found the solution here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement