我是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"。所以发件人发送消息给这个交换?如果有两个交换机,发送方向哪个交换机发送消息? 请帮忙。
答案 0 :(得分:1)
在这种情况下,您要发送到默认交换""
:
rabbitTemplate.convertAndSend(Application.queueName, "Hello from RabbitMQ!");
不是您的主题交换。
要发送到显式交换,请使用
rabbitTemplate.convertAndSend("someExchange", "routingKey", "Hello from RabbitMQ!");
修改强>
或者,您可以将默认交换配置为默认交换以外的其他交换。 template.setExchange("someExchange")
。