Cyrusmith Cyrusmith - 1 month ago 12
Java Question

Spring and AMQP RabbitMQ topic exchange not working

I'm trying to set up topic exchange on my spring app.
Here's my context configuration:




@Configuration
public class IntegrationConfig {

public final static String queueName = "my-queue";

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

}

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

@Bean
TopicExchange exchange() {
return new TopicExchange("my-exchange", false, true);
}

@Bean
Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("ru.interosite.*");
}

@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(listenerAdapter);
return container;
}

@Bean
ImageUploadReceiver receiver() {
return new ImageUploadReceiver();
}

@Bean
MessageListenerAdapter listenerAdapter(ImageUploadReceiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}

}




This is receiver class:




public class ImageUploadReceiver {
private CountDownLatch latch = new CountDownLatch(1);

public void receiveMessage(String message) {
System.out.println("Received ");
latch.countDown();
}

public CountDownLatch getLatch() {
return latch;
}
}




This is sender code:




@RequestMapping("/sendmessage")
@ResponseBody
public String sendMessage() {
rabbitTemplate.convertAndSend("ru.interosite.1", "ttt1233");
try {
imageUploadReceiver.getLatch().await(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Msg received";
}




So I'm sending message to topic exchange using binding key "ru.interosite.1" to the queue that was bound with pattern "ru.interosite.*". I used these key and pattern when tried sample from https://www.rabbitmq.com/tutorials/tutorial-five-java.html and they worked fine.

But inside String AMQP it does not work, i.e. receiver never gets called. It called only if binding key and pattern are completely the same as if I were using DirectExchange.

Am I missing something here?

Answer

You don't show the config for the RabbitTemplate, but I guess it is with default options.

To send a message to the my-exchange you must specify it directly:

rabbitTemplate.convertAndSend("my-exchange", "ru.interosite.1", "ttt1233");
Comments