我有一條路由(駝峯2.17.3),它使用豐富的DSL調用休息服務並將結果聚合到郵件正文中。不過,我遇到了序列化問題。這是我正在嘗試的。我的路線是這樣的:如何在AggregationStrategy中將郵件正文轉換爲pojo
rest("myService").produces("application/json")
.get("test")
.param().name("text").required(true).type(RestParamType.query).description("The text to be processed.").endParam()
.to("direct:StepA")
;
from("direct:StepA")
.removeHeader("CamelHttpQuery")
.removeHeader("CamelHttpRawQuery")
.enrich("netty4-http://myOtherService:8080/endpoint?input=${header.text}", new MyAggregator())
.to("direct:StepB")
;
from("direct:StepB")
// not really implemented yet
.transform().simple("Query: ${header.text}\nBody: ${body}")
;
正如你看到的,我想用充實()DSL在調出了一些現有的服務和聚合這些結果以形成新的消息體進行進一步的處理。我需要將該休息調用的結果從Json轉換爲MyResponse。我想用這個:
.unmarshal().json(JsonLibrary.Jackson, MyResponse.class)
但我需要它已經是我AggregationStrategy,它看起來像這樣內解組:
public class MyAggregator implements AggregationStrategy {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
final MyResponse intermediateResponse = oldExchange.getIn().getBody(MyResponse.class);
final MyAggregate response = new MyAggregate(oldExchange.getIn().getHeader("text", String.class), intermediateResponse);
newExchange.getIn().setBody(response);
return newExchange;
}
返回null,但是,當我說getBody(.. )。所以,我學到了類型轉換器,並試圖使用這樣的系統可以自動將轉換爲我喜歡的類型:
public class MyConverter extends TypeConverterSupport {
private static final ObjectMapper MAPPER =
new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
@Override
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) throws TypeConversionException {
try {
return (T)MAPPER.readValue(value.toString(), MyResponse.class);
} catch (IOException e) {
throw new TypeConversionException(value, type, e);
}
}
然後在我的主:
public static void main(String... args) throws Exception {
Main main = new Main();
main.setApplicationContextUri("classpath:app-ctx.xml");
for (final CamelContext ctx : main.getCamelContexts()) {
ctx.getTypeConverterRegistry().addTypeConverter(MyResponse.class, String.class, new MyConverter());
}
main.run(args);
}
但這似乎並沒有改變結果。在我的聚合器中,MyResponse仍然爲空。我錯過了一些關於如何設置此類型轉換的信息,並希望有人能夠指引我朝着正確的方向發展。