2010年12月22日 星期三

How to dynamically update/remove routers?

public class DynamicRoutesTest extends CamelTestSupport {

@Test
public void routesCanBeCreatedDynamically() throws Exception {
MockEndpoint mock = setExpectedMessagesToMock("mock:out-endpoint", 1);

context.addRoutes(createDynamicRoute("dynamicRouteId",
"direct:in", "mock:out-endpoint"));

sendBody("direct:in", "payload to dynamic endpoint");

assertSatisfied(mock);
}

@Test
public void routesCanBeUpdatedDynamicallyToo() throws Exception {
// we're going to change the destination endpoint so the old
one should receive no exchanges and the new on one.
MockEndpoint oldDestination =
setExpectedMessagesToMock("mock:out-endpoint", 0);
MockEndpoint newDestination =
setExpectedMessagesToMock("mock:new-out-endpoint", 1);

context.addRoutes(createDynamicRoute("dynamicRouteId",
"direct:in", "mock:out-endpoint"));

//stop the route by its id
context.stopRoute("dynamicRouteId");

context.addRoutes(redirectTrafficToDifferentEndpoint("dynamicRouteId",
"mock:new-out-endpoint"));

sendBody("direct:in", "payload to dynamic endpoint");

assertSatisfied(oldDestination, newDestination);

}

public RouteBuilder createDynamicRoute(final String id, final
String uri, final String touri) {
return new RouteBuilder() {
public void configure() throws Exception {
from(uri).id(id).to(touri);
}
};
}

public RouteBuilder redirectTrafficToDifferentEndpoint(final
String id, final String newDestination) {
return new RouteBuilder() {
public void configure() throws Exception {
RouteDefinition old = getContext().getRouteDefinition(id);

for (FromDefinition from : old.getInputs()) {
from(from.getUri()).id(old.getId()).to(newDestination);
}
}
};
}

private MockEndpoint setExpectedMessagesToMock(String mockUri, int
expectedMessages) {
MockEndpoint mock = getMockEndpoint(mockUri);
mock.expectedMessageCount(expectedMessages);
return mock;
}

private void assertSatisfied(MockEndpoint... mocks) throws
InterruptedException {
for (MockEndpoint mock : mocks) {
mock.await(1, TimeUnit.SECONDS);
mock.assertIsSatisfied();
}
}
}


Quoted above code segments from

http://camel.465427.n5.nabble.com/How-to-update-remove-camel-route-td478637.html

沒有留言:

張貼留言