简体   繁体   English

如何在 RabbitMQ 消息上添加 x-delay header?

[英]How to add x-delay header on RabbitMQ message?

I'm trying to add a header x-delay on my messages using a instance of MessagePostProcessor but it gives me an exception saying:我正在尝试使用MessagePostProcessor的实例在我的消息上添加 header x-delay ,但它给了我一个异常说:

java.lang.UnsupportedOperationException: MessageHeaders is immutable java.lang.UnsupportedOperationException:MessageHeaders 是不可变的

import org.springframework.messaging.Message
import org.springframework.messaging.core.MessagePostProcessor
import org.springframework.stereotype.Component

@Component
class AmpqRoutingKeyStrategy {

    private static CUSTOM_DELAY = 120000

    MessagePostProcessor get() {
        return withDelay(CUSTOM_DELAY)
    }

    static MessagePostProcessor withDelay(Integer milliSeconds) {
        return new MessagePostProcessor() {
            @Override
            Message postProcessMessage(Message message) {
                message.getHeaders().put('x-delay', milliSeconds)
                return message
            }
        }
    }
}

The example above is used in many articles about this topic, I know that we have the option to add the x-delay header but how can I do it without raising this exception?上面的例子在很多关于这个主题的文章中都有使用,我知道我们可以选择添加x-delay header 但是我怎样才能在不引发这个异常的情况下做到这一点?

The documentation says: 文档说:

IMPORTANT: This class is immutable.重要提示:此 class 是不可变的。 Any mutating operation such as put(..), putAll(..) and others will throw UnsupportedOperationException.任何变异操作,例如 put(..)、putAll(..) 和其他操作都会抛出 UnsupportedOperationException。

The solution is to recreate the message:解决方案是重新创建消息:

static MessagePostProcessor withDelay(Integer milliSeconds) {
    return new MessagePostProcessor() {
        @Override
        Message postProcessMessage(Message message) {
            return org.springframework.messaging.support.MessageBuilder
                .fromMessage(message)
                .setHeader("x-delay", milliseconds)
                .build()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM