转载自:https://blog.csdn.net/zht741322694/article/details/79828088
spring-boot整合RabbitMQ(单生产以及多消费)
单生产多消费相比于单生产单消费来说只是多了一个消费者而已,需要注意的是,这两个消费者都是监听一个消息队列并且默认情况下针对生产者发布的消息是进行分摊的,而不是同时拥有消费,
因为rabbitmq默认的消费确认原则是生产者发布了一个消息,只要有一个消费者消费了,那么此消息会立即从队列中移除,不会管这个消息的消费时长以及是否成功。这种方式存在着一个问题就是,如果此消费者拿到此消息之后,处理超时异常了等,那么就造成了此消息没有被成功消费而丢失,想要解决这个问题可以关闭rabbitMQ的自动消息确认功能,从而在代码中进行手动确认。
手动确认一定要确保消息处理后消息回执,否则将造成消息二次消费以及消息积压到队列中。举个栗子:默认情况下如果生产者发送了一条消息到消息队列中,两个消费者只能有一个消费者能够消费到此消息,下面直接上代码:
消费者1:
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* 消费者监听消息队列
*/
@Component
@RabbitListener(queues = "hello-queue")
public class QueueListener {
@RabbitHandler
public void proces(String message){
System.out.println("消费者:"+message);
}
}
消费者2:
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* 消费者监听消息队列
*/
@Component
@RabbitListener(queues = "hello-queue")
public class QueueListener2 {
@RabbitHandler
public void proces(String message){
System.out.println("消费者2:"+message);
}
}
生产者:
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rabbitMq")
public class HelloRabbitMQController {
@Autowired
private AmqpTemplate amqpTemplate;
/**实现消息的发送*/
@RequestMapping(value = "/helloQueue",method = RequestMethod.GET)
public void send(){
String message = "this is queue test!";
for(int i=0;i<10;i++){ --如果这里只是发送一次,只会有一个消费者能够消费到此消息,多条消息是均摊的
this.amqpTemplate.convertAndSend("hello-queue",message);
}
}
}
结果:
消费者2:this is queue test!
消费者:this is queue test!
消费者:this is queue test!
消费者2:this is queue test!
消费者:this is queue test!
消费者2:this is queue test!
消费者:this is queue test!
消费者2:this is queue test!
消费者:this is queue test!
消费者2:this is queue test!
————————————————
版权声明:本文为CSDN博主「Yeah-小海」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zht741322694/article/details/79828088