使用“接收后”
MessagePostProcessor
添加
contentType
入站邮件的标头。
从2.0版开始,您可以将MPP添加到容器工厂。
对于早期版本,您可以重新配置。。。
@SpringBootApplication
public class So47424449Application {
public static void main(String[] args) {
SpringApplication.run(So47424449Application.class, args);
}
@Bean
public ApplicationRunner runner(RabbitListenerEndpointRegistry registry, RabbitTemplate template) {
return args -> {
SimpleMessageListenerContainer container =
(SimpleMessageListenerContainer) registry.getListenerContainer("myListener");
container.setAfterReceivePostProcessors(m -> {
m.getMessageProperties().setContentType("application/json");
return m;
});
container.start();
// send a message with no content type
template.setMessageConverter(new SimpleMessageConverter());
template.convertAndSend("foo", "{\"bar\":\"baz\"}", m -> {
m.getMessageProperties().setContentType(null);
return m;
});
template.convertAndSend("foo", "{\"bar\":\"qux\"}", m -> {
m.getMessageProperties().setContentType(null);
return m;
});
};
}
@Bean
public Jackson2JsonMessageConverter converter() {
return new Jackson2JsonMessageConverter();
}
@RabbitListener(id = "myListener", queues = "foo", autoStartup = "false")
public void listen(Foo foo) {
System.out.println(foo);
if (foo.bar.equals("qux")) {
throw new MessageConversionException("test");
}
}
public static class Foo {
public String bar;
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
@Override
public String toString() {
return "Foo [bar=" + this.bar + "]";
}
}
}
如您所见,由于它修改了源消息,因此修改后的标头在错误处理程序中可用。。。
2017-11-22 09:39:26.615 WARN 97368---[cTaskExecutor-1]IngerroHandler$DefaultExceptionStrategy:致命消息转换错误;消息被拒绝;如果这样配置,它将被丢弃或路由到死信交换:(正文:{“bar”:“qux”}消息属性[头={},
contentType=应用程序/json
,contentEncoding=UTF-8,contentLength=0,receivedDeliveryMode=PERSISTENT,priority=0,redelived=false,receivedExchange=,receivedrootingkey=foo,deliveryTag=2,consumerTag=amq。ctag-re1kcxKV14L\u nl186stM0w,consumerQueue=foo]),contentType=application/json,contentEncoding=UTF-8,contentLength=0,receivedDeliveryMode=PERSISTENT,priority=0,redelived=false,receivedExchange=,receivedrootingkey=foo,deliveryTag=2,consumerTag=amq。ctag-re1kcxKV14L\U nl186stM0w,consumerQueue=foo])