我正在尝试启动一个Spring Boot应用程序,该应用程序具有由此配置类配置的RabbitMQ:
@Configuration
public class RabbitConfig implements RabbitListenerConfigurer {
public static final String AMQP_EXCHANGE_NAME = "test-queue";
@Bean
public Exchange accessExchange() {
return new DirectExchange(AMQP_EXCHANGE_NAME);
}
@Bean
public Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(AMQP_EXCHANGE_NAME);
}
@Bean
public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public MappingJackson2MessageConverter consumerJackson2MessageConverter() {
return new MappingJackson2MessageConverter();
}
@Bean
public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
return rabbitTemplate;
}
@Bean
public DefaultMessageHandlerMethodFactory messageHandlerMethodFactory() {
DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setMessageConverter(consumerJackson2MessageConverter());
return factory;
}
@Override
public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
registrar.setMessageHandlerMethodFactory(messageHandlerMethodFactory());
}
但我收到错误no queue 'test-queue' in vhost '/'
:
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'test-queue' in vhost '/', class-id=50, method-id=10)
at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:509) ~[amqp-client-4.2.0.jar:4.2.0]
at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:340) ~[amqp-client-4.2.0.jar:4.2.0]
at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:162) ~[amqp-client-4.2.0.jar:4.2.0]
at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:109) ~[amqp-client-4.2.0.jar:4.2.0]
at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:643) ~[amqp-client-4.2.0.jar:4.2.0]
at com.rabbitmq.client.impl.AMQConnection.access$300(AMQConnection.java:47) ~[amqp-client-4.2.0.jar:4.2.0]
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:581) ~[amqp-client-4.2.0.jar:4.2.0]
... 1 common frames omitted
只有在定义了以下侦听器时才会出现此问题:
@Transactional
@RabbitListener(queues = RabbitConfig.AMQP_EXCHANGE_NAME)
public void doSomething(TestDTO dto) {
...
}
似乎我正在尝试从队列中消耗,但是队列中没有创建。如果我通过RabbitMQ管理界面创建队列,则不会发生错误。
有没有办法自动创建此队列,所以我没有收到此错误?
答案 0 :(得分:1)
你没有显示你的Queue
豆。您的配置似乎也没有RabbitAdmin
(自动声明队列,交换,绑定所需)。
答案 1 :(得分:0)
@Autowired
private AmqpAdmin amqpAdmin;
@Bean
public Binding binding(Queue queue, DirectExchange exchange) {
// automatically create this queue, so you do not get this error.
amqpAdmin.declareQueue(queue);
return BindingBuilder.bind(queue).to(exchange).with(AMQP_EXCHANGE_NAME);
}