Apache Camel whenExchangeReceived和whenAnyExchangeReceived-访问Exchange

时间:2019-02-18 23:17:23

标签: java apache-camel

我正在尝试通过OUT修改模拟生产者的whenAnyExchangeReceived消息。 但是在我看来,我无法访问路由内现有的交换,而是获取新的交换。 如何修改OUT消息并将修改后的消息返回给原始路由使用者。

MockEndpoint vmMock = getMockEndpoint("mock:vm:client-search");
vmMock .whenAnyExchangeReceived(exchange -> {
       log.info(" *** Exchange arrived to MOCK ");
       log.info("Exchange Mock Exchange", exchange);
       log.info("Exchange Mock Exchange ID", exchange.getExchangeId());
       log.info("Exchange Mock Route ID", exchange.getFromRouteId());
       log.info("Exchange Mock Properties", exchange.getProperties());
       log.info("Exchange Mock Body", exchange.getIn().getBody(SearchRequest.class));

       exchange.getIn().setBody("MOCK-OK-IN", String.class);
       exchange.getOut().setBody("MOCK-OK", String.class);
    });

与拦截器的行为相同

     interceptSendToEndpoint("vm:companies-search")
                    .skipSendToOriginalEndpoint()
                    .process(exchange -> {
   // trying to access exchange and set body in the same way as in example above - but failing as 
             });

更新:《骆驼在行动2》(出色)中的测试示例

public class MirandaTest extends CamelTestSupport {

    Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("jetty://http://localhost:9080/service/order")
                        .process(new OrderQueryProcessor())
                        .to("mock:miranda");
            }
        };
    }

    @Test
    public void testMiranda() throws Exception {
        context.setTracing(true);

        MockEndpoint mock = getMockEndpoint("mock:miranda");
        mock.expectedBodiesReceived("ID=123");
        mock.whenAnyExchangeReceived(exchange -> {
            // No previous exchange information here
            log.info(" *** Exchange arrived to MOCK ");
            log.info("Exchange Mock Exchange", exchange);
            log.info("Exchange Mock Exchange ID", exchange.getExchangeId());
            log.info("Exchange Mock Route ID", exchange.getFromRouteId());
            log.info("Exchange Mock Properties", exchange.getProperties());
            log.info("Exchange Body", exchange.getIn(String.class));

            exchange.getIn().setBody("MOCK-OK-IN", String.class);
        });

        String out = template.requestBody("http4://localhost:9080/service/order?id=123", null, String.class);
        assertEquals("MOCK-OK-IN", out);

        assertMockEndpointsSatisfied();
    }

    private class OrderQueryProcessor implements Processor {

        public void process(Exchange exchange) throws Exception {
            String id = exchange.getIn().getHeader("id", String.class);
            exchange.getIn().setBody("ID=" + id);
        }

    }
}

0 个答案:

没有答案