![](/img/trans.png)
[英]Not able to publish a message onto RabbitMQ using header exchange with Spring Boot
[英]How to identify the exchange to which the message is routed to in Spring boot rabbitmq?
我是Spring AMQP的新手,只是想了解使用注释的RabbitMQ Java配置。 这里是示例代码。
发件人代码-
@Component
public class Runner implements CommandLineRunner {
private final RabbitTemplate rabbitTemplate;
private final Receiver receiver;
private final ConfigurableApplicationContext context;
public Runner(Receiver receiver, RabbitTemplate rabbitTemplate,
ConfigurableApplicationContext context) {
this.receiver = receiver;
this.rabbitTemplate = rabbitTemplate;
this.context = context;
}
@Override
public void run(String... args) throws Exception {
System.out.println("Sending message...");
rabbitTemplate.convertAndSend(Application.queueName, "Hello from RabbitMQ!");
receiver.getLatch().await(10000, TimeUnit.MILLISECONDS);
context.close();
}
}
因此,在这里,在convertAndSend()中,仅指定了路由密钥。 没有给出交易所名称。
配置文件如下图所示-
@SpringBootApplication
public class Application {
final static String queueName = "spring-boot";
final static String HOST = "120.27.114.229";
final static String USERNAME = "root";
final static String PASSWORD = "root";
final static int PORT = 5672;
@Bean
Queue queue() {
return new Queue(queueName, false);
}
@Bean
TopicExchange exchange() {
return new TopicExchange("spring-boot-exchange");
}
@Bean
Binding binding(Queue queue, TopicExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(queueName);
}
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setHost(HOST);
connectionFactory.setPort(PORT);
connectionFactory.setUsername(USERNAME);
connectionFactory.setPassword(PASSWORD);
connectionFactory.setVirtualHost("/");
//����Ҫ����,��Ϣ�Ļص�
connectionFactory.setPublisherConfirms(true);
return connectionFactory;
}
@Bean
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(queueName);
container.setMessageListener(listenerAdapter);
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
}
此处定义了TopicExchange bean,名称为“ spring-boot-exchange”。 因此,发件人将消息发送到此交换机? 如果有两个交换,发件人将消息发送到哪个交换? 请帮忙。
在这种情况下,您将发送到默认交换机""
:
rabbitTemplate.convertAndSend(Application.queueName, "Hello from RabbitMQ!");
不是您的主题交流。
要发送给明确的交易所,请使用
rabbitTemplate.convertAndSend("someExchange", "routingKey", "Hello from RabbitMQ!");
编辑
或者,您可以将默认交换配置为默认交换以外的其他内容。 template.setExchange("someExchange")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.