Reputation: 636
I'm trying to add a header x-delay
on my messages using a instance of MessagePostProcessor
but it gives me an exception saying:
java.lang.UnsupportedOperationException: MessageHeaders is immutable
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?
Upvotes: 1
Views: 738
Reputation: 3366
The documentation says:
IMPORTANT: This class is immutable. Any mutating operation such as put(..), putAll(..) and others will throw 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()
}
}
}
Upvotes: 2