赞
踩
再写项目时将rabbitMq的创建放在了生产端,然后就出现了队列没有创建的错误,在查了资料之后找到了错误之处
可通过配置 RabbitAdmin 来实现自动创建队列
源码:
this.rabbitTemplate.execute((channel) -> { this.declareExchanges(channel, (Exchange[])exchanges.toArray(new Exchange[exchanges.size()])); this.declareQueues(channel, (Queue[])queues.toArray(new Queue[queues.size()])); this.declareBindings(channel, (Binding[])bindings.toArray(new Binding[bindings.size()])); return null; });
- 1
- 2
- 3
- 4
- 5
- 6
使用:
@Bean public RabbitAdmin rabbitAdmin(ConnectionFactory defaultConnectionFactory){ return new RabbitAdmin(defaultConnectionFactory); } // 在初始化RabbitTemplate时 将队列创建 @Bean public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory , RabbitAdmin rabbitAdmin) { RabbitTemplate template = new RabbitTemplate(connectionFactory); //成功回调 template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean b, String s) { System.out.println(correlationData.toString()); System.out.println(b); System.out.println(s); } }); // 使用RabbitAdmin =====> rabbitAdmin.initialize(); // 开启mandatory模式(开启失败回调) template.setMandatory(true); //失败回调 template.setReturnsCallback(new RabbitTemplate.ReturnsCallback() { @Override public void returnedMessage(ReturnedMessage returnedMessage) { System.out.println(returnedMessage.getMessage()); System.out.println(returnedMessage.getExchange()); System.out.println(returnedMessage.getReplyCode()); System.out.println(returnedMessage.getReplyText()); System.out.println(returnedMessage.getRoutingKey()); } }); return template; }
配置 SimpleRabbitListenerContainerFactory 来实现自动创建队列
SimpleRabbitListenerContainerFactory 已经默认帮我们 创建了 RabbitAdmin对象
- 1
使用:
//并发数量
public static final int DEFAULT_MIN_CONCURRENT = 2;
public static final int DEFAULT_MAX_CONCURRENT = 24;
@Bean("customContainerFactory")
public SimpleRabbitListenerContainerFactory containerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer,
ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConcurrentConsumers(DEFAULT_MIN_CONCURRENT);//
factory.setMaxConcurrentConsumers(DEFAULT_MAX_CONCURRENT);//24
configurer.configure(factory, connectionFactory);
return factory;
}
RabbitAdmin : 管理 channel 可调用 this.declareQueues 创建队列
https://cloud.tencent.com/developer/article/1668606
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。