如何通过Spring集成从RabbitMQ获取标头

时间:2017-03-13 13:34:51

标签: spring-integration rabbitmq-exchange spring-rabbitmq

为了使用延迟交换,我使用这种方法通过“int:gateway”消息发送给RabbitMq:

void send(@Payload Notification request, @Header(MessageProperties.X_DELAY) Integer delay, @Header("routingKey") String routingKey);

我可以在RabbitMQ中看到标题正确显示: x-delay:-60000

但是,当我从RabbitMQ收到此消息时,如何获得此标头?

到目前为止,我收到了我之前作为Json发送的对象,但是如果我尝试获取标题,则会收到异常。

发送:

integration.xml文件:

<!-- Producing service -->
    <int:gateway id="gateway" default-request-channel="producingChannel" service-interface="Gateway"/>
    <!-- Producing service -->


<!-- Service => RabbitMQ (Producing) -->
    <int:chain input-channel="producingChannel">
        <int:object-to-json-transformer/>
        <int-amqp:outbound-channel-adapter exchange-name="${queuing.notifications-exchange}" routing-key-expression="headers.routingKey" mapped-request-headers="*"/>
    </int:chain>
    <!-- Service => RabbitMQ (Producing) -->

java文件中的网关:

void send(@Payload Notification request, @Header(MessageProperties.X_DELAY) Integer delay, @Header("routingKey") String routingKey);

接收:

integration.xml文件:

<!-- RabbitMQ => Service (Consuming) -->
    <int-amqp:inbound-channel-adapter channel="consumingChannel" queue-names="${queuing.operator.queue}" concurrent-consumers="${queuing.concurrent-consumers}" prefetch-count="${queuing.prefetch-count}" mapped-request-headers="*" error-channel="errorChannel" />
    <!-- RabbitMQ => Service (Consuming) -->


<!-- Routing -->
<int:chain input-channel="consumingChannel">
    <int:json-to-object-transformer type="Notification"/>
    <int:service-activator ref="workingService" method="processNotificationFromQueue"/>
</int:chain>
<!-- Routing -->

java文件中的WorkingService:

public void processNotificationFromQueue(Notification notification,
            @Header(MessageProperties.X_DELAY) Integer delay) { ...
 }

此处抛出异常:

Caused by: java.lang.IllegalArgumentException: required header not available: x-delay

1 个答案:

答案 0 :(得分:0)

您必须改为使用AmqpHeaders.RECEIVED_DELAY

由于您正确使用了正确的mapped-request-headers="*"默认DefaultAmqpHeaderMapper地图:

Integer receivedDelay = amqpMessageProperties.getReceivedDelay();
if (receivedDelay != null) {
    headers.put(AmqpHeaders.RECEIVED_DELAY, receivedDelay);
}