我试图在我的春季应用上设置主题交换。 这是我的上下文配置:
@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");
}
}
这是接收器类:
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;
}
}
这是发件人代码:
@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";
}
所以我使用绑定密钥" ru.interosite.1"向主题交换发送消息。到与模式绑定的队列" ru.interosite。*"。当我从https://www.rabbitmq.com/tutorials/tutorial-five-java.html尝试样本时,我使用了这些键和模式,并且它们工作正常。
但在String AMQP中它不起作用,即接收器永远不会被调用。只有当绑定密钥和模式与我使用DirectExchange时完全相同时,它才会调用。
我在这里错过了什么吗?
答案 0 :(得分:2)
您没有显示RabbitTemplate
的配置,但我猜它是默认选项。
要向my-exchange
发送消息,您必须直接指定:
rabbitTemplate.convertAndSend("my-exchange", "ru.interosite.1", "ttt1233");
答案 1 :(得分:1)
您也可以在兔子模板中设置交换:
@Configuration
public class IntegrationConfig {
// ... as above
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setExchange("my-exchange");
return template;
}
}
所以你可以发送消息:
public class MyController {
@Autowired
RabbitTemplate rabbitTemplate;
@RequestMapping("/sendmessage")
@ResponseBody
public String sendMessage() {
rabbitTemplate.convertAndSend("ru.interosite.1", "ttt1233");
// ... as above
}
}