赞
踩
- @Component
- @Slf4j
- public class RabbitMQConfig {
-
- private String queue;
-
- private String exchange;
-
- private String routingKey;
-
- @Value("${rabbitmq.config.queue}")
- public void setQueue(String queue) {
- log.info("队列名称="+queue);
- this.queue = queue;
- }
-
- @Value("${rabbitmq.config.exchange}")
- public void setExchange(String exchange) {
- log.info("交换机名称="+exchange);
- this.exchange = exchange;
- }
-
- @Value("${rabbitmq.config.routingKey}")
- public void setRoutingKey(String routingKey) {
- log.info("路由键="+routingKey);
- this.routingKey = routingKey;
- }
-
- @Bean
- public Queue myQueue() {
- return new Queue(this.queue, true);
- }
-
- @Bean
- public DirectExchange myExchange() {
- return new DirectExchange(this.exchange);
- }
-
-
- //将队列和交换机进行绑定,并指定路由键
- @Bean
- public Binding binding(Queue myQueue, DirectExchange myExchange) {
- return BindingBuilder.bind(myQueue).to(myExchange).with(this.routingKey);
- }
-
- }
- @RabbitListener(queues = "你定义的队列名称")
- public void exportExcel(String msg, Message message, Channel channel) throws Exception{
- channel.basicQos(1);
- //如果消息为字符串1,那么这个消息模拟需要处理很长时间
- if ("1".equals(msg)){
- Thread.sleep(10000);
- }
- System.out.println(msg);
- //无论如何都要将消息确认
- channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
- }
我在本地跑了这两个消费者,并往队列中丢了10条消息,0~9
消费者1效果:
消费者2效果:
消费者2读到了"1",并且堵塞了当前线程,消费者2就会消费完一条消息后一直从队列中拿消息进行消费,从而两个消费者不会出现干等的情况!
最后最后,如果此文章对你有帮助,请关注点赞!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。