如何用php做网站管理系统,长沙网站搭建,嘉兴网站建设公司电话,wordpress图片备用地址在RabbitMQ中#xff0c;CorrelationData是一个用于封装业务ID信息的类#xff0c;它主要在消息确认机制中发挥作用。以下是关于CorrelationData在RabbitMQ中的详细作用#xff1a;
封装业务ID信息#xff1a; 当发送消息时#xff0c;可以将业务ID信息封装在Correlation…在RabbitMQ中CorrelationData是一个用于封装业务ID信息的类它主要在消息确认机制中发挥作用。以下是关于CorrelationData在RabbitMQ中的详细作用
封装业务ID信息 当发送消息时可以将业务ID信息封装在CorrelationData对象中并作为参数传递给消息发送方法。这样在消息处理过程中可以方便地追踪和识别与该消息相关的业务信息。 消息确认机制 RabbitMQ支持消息确认机制即生产者发送消息后可以等待消费者的确认消息以确保消息已成功被消费者处理。 CorrelationData在这种机制中起到关键作用。生产者发送消息时可以将CorrelationData对象与消息一起发送。当消费者处理完消息后可以通过CorrelationData中的业务ID来确认该消息。 唯一性标识 CorrelationData对象内部通常包含一个id属性用于表示当前消息的唯一性。这个唯一性标识可以在整个消息处理流程中保持不变方便进行消息追踪和确认。 获取方式 在消费者端可以通过消息的headers属性来获取CorrelationData中的业务ID信息。例如在Spring AMQP中可以使用Message.getHeaders().get(“spring_returned_message_correlation”)来获取CorrelationData中的业务ID。 与DeliveryTag的区别 DeliveryTag是RabbitMQ自动为每条消息生成的唯一标识用于消息的确认和重试等机制。而CorrelationData则是业务层面上的唯一性标识用于标识和追踪与特定业务相关的消息。 综上所述CorrelationData在RabbitMQ中主要用于封装和传递与消息相关的业务ID信息以便在消息处理过程中进行追踪和确认。它通过与RabbitMQ的消息确认机制相结合为消息的可靠传递和处理提供了重要支持。
例子
Service
public class TestServiceImpl implements TestService {Autowiredprivate MsgLogMapper msgLogMapper;Autowiredprivate RabbitTemplate rabbitTemplate;Overridepublic ServerResponse send(Mail mail) {String msgId RandomUtil.UUID32();mail.setMsgId(msgId);MsgLog msgLog new MsgLog(msgId, mail, RabbitConfig.MAIL_EXCHANGE_NAME, RabbitConfig.MAIL_ROUTING_KEY_NAME);msgLogMapper.insert(msgLog);// 消息入库CorrelationData correlationData new CorrelationData(msgId);rabbitTemplate.convertAndSend(RabbitConfig.MAIL_EXCHANGE_NAME, RabbitConfig.MAIL_ROUTING_KEY_NAME, MessageHelper.objToMsg(mail), correlationData);// 发送消息return ServerResponse.success(ResponseCode.MAIL_SEND_SUCCESS.getMsg());}}其中的String msgId RandomUtil.UUID32(); 是自己随机生成的编码作为唯一的业务ID信息
对于DeliveryTag则是在消息手动确认的时候需要传给MQ的一个消息标识这个仅仅是消息的标识和业务没关系 使用如下
package com.atguigu.gulimall.consumertrue.listener;import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;/****此处用一个类下的两个方法来模拟消费者** author: jd* create: 2024-06-25*/
Component
public class MyConsumerListener {RabbitListener(bindings {QueueBinding(value Queue(consumer_queue_2),//绑定交换机exchange Exchange(value muscle_fanout_exchange, type fanout))})public void consumer2(String msg,Message message, Channel channel) throws Exception {long deliveryTag message.getMessageProperties().getDeliveryTag();try {System.out.println(消费者2 msg);channel.basicAck(deliveryTag, false); //手动确认 设置消息唯一标识} catch (Exception e) {channel.basicReject(deliveryTag, false);e.printStackTrace();}}}