使用RabbitMQ的时候,同一个消息可能会被消费者多次消费,那么该如何解决呢?
可以使用全局MessageID,解决幂等性的问题。
基于《消息中间件系列教程(13) -RabbitMQ-SpringBoot集成RabbitMQ》的环境,下面直接上代码进行讲解:
1.生产者,定义一个全局MessageID:
@Component
public class FanoutProducer {
@Autowired
private AmqpTemplate amqpTemplate;
/*public void send(String queueName) {
String msg = "my_fanout_msg:" + new Date();
System.out.println(msg + ":" + msg);
amqpTemplate.convertAndSend(queueName, msg);
}*/
public void send(String queueName) {
String msg = "my_fanout_msg:" + System.currentTimeMillis();
Message message = MessageBuilder.withBody(msg.getBytes()).setContentType(MessageProperties.CONTENT_TYPE_JSON)
.setContentEncoding("utf-8").setMessageId(UUID.randomUUID() + "").build();
System.out.println(msg + ":" + msg);
amqpTemplate.convertAndSend(queueName, message);
}
}
2.消费者:
@Component
public class FanoutSmsConsumer {
@RabbitListener(queues = "fanout_sms_queue")
public void process(Message message) throws Exception {
String messageId = message.getMessageProperties().getMessageId();
System.out
.println(Thread.currentThread().getName() + ",邮件消费者获取生产者消息msg:" + new String(message.getBody(), "UTF-8")
+ ",messageId:" + messageId);
/*if(hasFinished(messageId)){
//如果消息处理完了,则直接完成,不消费信息
return;
}*/
}
}
在生产者控制台和消费者控制台,打印:
本文代码已上传至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/SpringBoot-RabbitMQ-Demo.git