//扩展CamelTestSupport
@Produce
private ProducerTemplate template;
@EndpointInject(uri = "mock:out")
private MockEndpoint mock;
@Test
public void testSplitAggregateConvertOrder(){
List<InOrder> inOrderList = new ArrayList<InOrder>();
InOrder inOrder1 = new InOrder();
inOrder1.setId("1");
inOrderList.add(inOrder1);
InOrder inOrder2 = new InOrder();
inOrder2.setId("2");
inOrderList.add(inOrder2);
InOrder inOrder3 = new InOrder();
inOrder3.setId("3");
inOrderList.add(inOrder3);
template.sendBody("direct:start", inOrderList);
Exchange outList = mock.getReceivedExchanges().get(0);
List<OutOrder> outOrderList = outList.getIn().getBody(List.class);
for(OutOrder outOrder : outOrderList){
System.out.println("####### mockResult id : "+outOrder.getId());
}
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
context.getTypeConverterRegistry().addTypeConverter(OutOrder.class, InOrder.class, new MyOrderTypeConverter());
from("direct:start")
.split(body(), new AggregationStrategy() {
@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
List<OutOrder> orders = new ArrayList<OutOrder>();
OutOrder newOrder = newExchange.getIn().getBody(OutOrder.class);
orders.add(newOrder);
newExchange.getIn().setBody(orders);
return newExchange;
}
List<OutOrder> orders = oldExchange.getIn().getBody(List.class);
OutOrder newOutOrder = newExchange.getIn().getBody(OutOrder.class);
orders.add(newOutOrder);
oldExchange.getIn().setBody(orders);
return oldExchange;
}
})
.convertBodyTo(OutOrder.class)
.end() //splitter ends here and the exchange body is now List<OutOrder>
.to("mock:out");
}
};
}
private static class MyOrderTypeConverter extends TypeConverterSupport {
@SuppressWarnings("unchecked")
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
// converter from inorder to outorder bean
OutOrder order = new OutOrder();
order.setId(Integer.parseInt(((InOrder) value).getId()));
return (T) order;
}
}
private static class OutOrder {
private int id;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
private static class InOrder {
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
我只需要修复列表大小,如{1,2},但结果全部返回,结果为{1,2,3}。
我只想在结果大小等于2时,打破聚合。有人帮我吗?
答案 0 :(得分:0)
具有聚合策略的拆分器将始终聚合所有拆分的子消息。因此,如果有3个子消息,则会获得3个聚合。但是因为它的java代码,你可以自己跟踪它,如果你已经聚合了2条消息,那么你可以在调用它时忽略第3条消息。