Camel:根据消息的来源省略部分路由

ar7v8xwq  于 2022-11-07  发布在  Apache
关注(0)|答案(1)|浏览(188)

我有两条路线:

.from("A")
.to("C")
.to("B");

.from("C")

* some processing logic*

.to("D");

是否可以建立第二条路线,以使:

  • 当报文来自第一路由时,省略部分或全部逻辑;
  • 当报文直接到达第二路由时,使用的逻辑是?
ujv3wf0j

ujv3wf0j1#

您可以在路由上设置交换属性。然后您可以评估filter或choice中的值来分支或改变路由逻辑。我建议不要做比这更复杂的事情,以避免路由之间不必要的耦合。

范例:

package org.example;

import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

public class ExampleRouteTests extends CamelTestSupport {

    @Test
    public void shouldReturnSentBody() throws Exception {

        final String testMessage = "AAAA";

        MockEndpoint resultMockEndpoint = getMockEndpoint("mock:result");
        resultMockEndpoint.expectedMessageCount(1);
        resultMockEndpoint.message(0).body().isEqualTo(testMessage);

        template.sendBody("direct:a", testMessage);

        resultMockEndpoint.assertIsSatisfied();
    }

    @Test
    public void shouldReturnBBBB() throws Exception {

        MockEndpoint resultMockEndpoint = getMockEndpoint("mock:result");
        resultMockEndpoint.expectedMessageCount(1);
        resultMockEndpoint.message(0).body().isEqualTo("BBBB");

        template.sendBody("direct:b", null);

        resultMockEndpoint.assertIsSatisfied();
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {

            @Override
            public void configure() throws Exception {

                from("direct:a")
                    .setProperty("From", constant("A"))
                    .to("direct:c");

                from("direct:b")
                    .setProperty("From", constant("B"))
                    .to("direct:c");

                from("direct:c")
                    .filter(exchangeProperty("From").isNotEqualTo("A"))
                        .log("Processing message")
                        .setBody(constant("BBBB"))
                    .end()
                    .log("body: ${body}")
                    .to("mock:result");

            }
        };
    }
}

相关问题