Tel*_*pdx 1 json apache-camel unmarshalling
是否有使用自定义聚合策略将 JSON 解组为 Apache Camel 中的 POJO 的优雅方法?
我的简单路由从 SQS 获取一条消息,该消息是 JSON。此消息用作另一个服务的输入,而后者又根据消息内容让我知道原始消息应发布到的服务的 URL 是什么。
使用 AggregationStrategy 丰富 EIP 非常适合这一点。但是,我无法弄清楚如何在路由中优雅地将 JSON 解组为 POJO。我可以通过 ObjectMapper 做到这一点,但这看起来很难看。有没有更好的处理方法?一些我还没见过的神奇骆驼酱?
public RouteBuilder route() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("aws-sqs://" + sqsName + "?amazonSQSClient")
.setHeader("Content-Type",simple("application/json"))
.enrich()
.simple("http4://localhost:8080/getUrl")
.aggregationStrategy(new AggregationStrategy() {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
String aPojoStr = newExchange.getIn().getBody(String.class);
ObjectMapper mapper = new ObjectMapper();
RestAnswererResponse responosePojo;
try {
responosePojo = mapper.readValue(aPojoStr, RestAnswererResponse.class);
} catch (JsonParseException e) {
throw new RuntimeException("Error parsing response to pojo", e);
} catch (JsonMappingException e) {
throw new RuntimeException("Error parsing response to pojo", e);
} catch (IOException e) {
throw new RuntimeException("Error parsing response to pojo", e);
}
oldExchange.getIn().setHeader("URL", responosePojo.getURL());
return oldExchange;
}
})
.toD("http4://${header" + "URL + "}/postToAck);
}
};
}
Run Code Online (Sandbox Code Playgroud)
编辑:只是为了进一步澄清我的路线需要如何工作:
JSON 消息的内容需要发布到服务,该服务根据原始消息的上下文确定消息应该发布到的最终 URL(这是特定于上下文的发现服务)。发现服务仅返回最终目的地的 URL。
{"url":"somehost:port"}
Run Code Online (Sandbox Code Playgroud)您可以使用JSON 数据格式来解组消息,而不是使用ObjectMapper.
使用丰富时,我发现创建direct它调用的路由很有用。我发现这更容易理解、模拟、测试,你可以给它不同的错误处理和重新传递策略。
from("aws-sqs://" + sqsName + "?amazonSQSClient")
.setHeader("Content-Type",simple("application/json"))
.enrich("direct:other", strategy)
.toD("http4://${header" + "URL + "}/postToAck);
from("direct:other")
.to("http4://localhost:8080/getUrl")
.unmarshal().json(JsonLibrary.Jackson, RestAnswererResponse.class);
Run Code Online (Sandbox Code Playgroud)
所有策略需要做的就是提取 URL 并根据需要设置标题。