我有以下场景
路由策略:
@Slf4j
@RequiredArgsConstructor
public class LoggingPolicy extends RoutePolicySupport {
private final String greeting;
@Override
public void onExchangeBegin(Route route, Exchange exchange) {
super.onExchangeBegin(route, exchange);
log.info("%s from LoggingPolicy".formatted(greeting));
}
}
基本路由构建器:
public abstract class BaseRouteBuilder
extends RouteBuilder {
@Override
public void configure() throws Exception {
onException()
.handled(true)
.log("Exception occured")
.end();
configRoutes();
}
abstract void configRoutes();
}
两种实现:
@Component
public class HelloRouteBuilder extends BaseRouteBuilder {
@Override
void configRoutes() {
from("timer:hello?repeatCount=1")
.routeId("HelloRoute")
.routePolicy( new LoggingPolicy("Hello"))
.log("HelloRoute Completed");
}
}
@Component
public class ByeRouteBuilder extends BaseRouteBuilder {
@Override
void configRoutes() {
from("timer:bye?repeatCount=1")
.routeId("ByeRoute")
.routePolicy( new LoggingPolicy("Bye"))
.log("ByeRoute Completed");
}
}
最后还有另一个 RouteBuilder - 不是从 BaseRouteBuilder 继承的
@Component
public class AnotherRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:another?repeatCount=1")
.routeId("AnotherRoute")
.log("AnotherRoute Completed");
}
}
一切都按预期进行。
我现在想做的是将 LoggingPolicy 委托给 BaseRouteBuilder,以便
LoggingPolicy 应用于继承形式
BaseRouteBuilder
的所有 RouteBuilder 中的所有路由(在本例中为 HelloRoute
和 ByeRoute
但不是 AnotherRoute
)
构造函数参数 (
greeting
) 默认为 "Hello"
,但可以在路由构建器中覆盖。
在我的实际用例中,我有 100 多个 RouteBuilder,我想向所有这些添加 LoggingPolicy。其中大多数都有默认参数,但我需要覆盖一些路由的参数。
经过相当多的实验,我找到了以下解决方案
public abstract class BaseRouteBuilder
extends RouteBuilder {
@Override
public void configure() throws Exception {
onException()
.handled(true)
.log("Exception occurred")
.end();
configRoutes();
configureRoutes(getContext()).getRoutes()
.forEach(route -> route.routePolicy(
getLoggingPolicy()));
}
abstract void configRoutes();
protected RoutePolicy getLoggingPolicy() {
return new LoggingPolicy(
getLoggingPolicyGreeting());
}
protected String getLoggingPolicyGreeting() {
return "Hola"; // Default greeting
}
}
现在在子路由中,我可以覆盖
getLoggingPolicyGreeting
来修改 greeting
的默认 RouteBuilder
甚至整个 LoggingPolicy
使用 getLoggingPolicyGreeting
类似
@Component
public class ByeRouteBuilder extends BaseRouteBuilder {
@Override
void configRoutes() {
from("timer:bye?repeatCount=1")
.routeId("ByeRoute")
.log("ByeRoute Completed");
}
@Override
protected String getLoggingPolicyGreeting() {
return "Bye";
}
}