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);
}
}
In RabbitMQ, a producer never sends a message directly to a queue. Instead, it uses an exchange as a routing mediator. Therefore, the exchange decides if the message goes to one queue, to multiple queues, or is simply discarded.
In AMQP 0-9-1, the broker can generate a unique queue name on behalf of an app. To use this feature, pass an empty string as the queue name argument: The same generated name may be obtained by subsequent methods in the same channel by using the empty string where a queue name is expected.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With