我怎样才能得到 correlationId?

how can i get correlationId?

在我的项目中(spring-rabbit..),在模板上设置固定的 ReplyTo queue,我对 RPC 使用 convertSendAndReceive 方法。

我知道自动生成 correlationId。

我可以在使用该方法之前设置 correlationId 吗?

这是模板。

@Bean   
public RabbitTemplate rabbitTemplate() {
    RabbitTemplate template = new RabbitTemplate(connectionFactory());
    template.setMessageConverter(jsonMessageConverter());       
    template.setRoutingKey(AmqpConstants.JOB_QUEUE_NAME);
    template.setExchange(AmqpConstants.JOB_EXCHANGE_NAME);
    template.setQueue(AmqpConstants.JOB_QUEUE_NAME);    
    template.setReplyQueue(new Queue(AmqpConstants.JOB_REPORT_QUEUE_NAME)); 

    template.setReplyTimeout(replyTimeoutMilliseoconds);

    return template;
}

代码

jobReport = (ApiJobReport)rabbitTemplate.convertSendAndReceive(
                AmqpConstants.JOB_EXCHANGE_NAME, 
                AmqpConstants.JOB_QUEUE_NAME, 
                jobMessage, new MessagePostProcessor() {

                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties().setCorrelationId("correlationid1234".getBytes());
                        return message;
                    }
                }); 

在postProcessMessage中,设置correlationId为"correlationid1234"。 但是 RabbitMQ Management 显示如下。

消息属性:

correlation_id: 23316fe6-0c15-46f6-9bed-5f3abf22a594

优先级:0 delivery_mode: 2 headers:
TypeId: com.example.model.apijob content_encoding: UTF-8 content_type: application/json

如图所示,set correlationId 已更改为 RabbitTemplate messageTag value(UUID)。我正在观看 RabbitTemplate 源代码,但我不明白为什么如果 correlationKey 为空,它会更改 correlationId。

RabbitMQ Management

如果您使用 sendAndReceive()(而不是 convertSendAndReceive());如果设置了 correlationId 消息 属性,模板会将其保存;在出站消息中使用自己的 correlationId 并在回复消息中恢复原始 correlationId。

convertSendAndReceive()的上下文中你的意思不清楚;您不能在调用之前设置 correlationId,因为在转换发生之前没有消息。

您可以将其设置为 MessagePostProcessor,但效果不佳。

也许如果你能解释一下你想做什么,我可以提出一些其他建议。