Camel 组件在启动时的参数化

Parameterization of Camel Component at startup

我想在 class 实例化时在 Apache Camel Component 中设置 class 属性。我该怎么做?

我有一个非常简单的 Spring 启动应用程序:

@SpringBootApplication
@ComponentScan(basePackages = "xyz.abc.myPackage")
public class RouteHandler_ARCHIVE {

}

拉取同样位于包 XYZ.abc.myPackage 中的 Apache Camel 组件:

@Component
public class Route_ARCHIVE_REST extends RouteBuilder {

    private String _deviceName;
    private String _deviceProperty;
    Set<String> _batchBuffer = new HashSet<>();
    int _batchBufferLimit = 10;

    @Override
    public void configure() throws Exception {

        from("timer:mytimer?repeatCount=1") //
                .setBody(simple("${null}")) //
                .setHeader(Exchange.CONTENT_TYPE, simple("text/event-stream"))
                .setHeader("CamelHttpMethod", simple("GET"))
                .to("myUrl/" //
                    + _deviceName + "::" + _deviceProperty //
                    + "?disableStreamCache=true" //
                ) //
                .process(data -> {
                    ... my process ...
                })
                .log("${body}")
                .to(toEndpoint);
    }

}

我想用 _deviceName_deviceProperty 的不同值启动此路线的多个实例。目前我只有复制 class N 次并对不同值进行硬编码的想法——这绝对不是很有效;)

由于我没有显式实例化 Component class(由 @ComponentScan 完成),我如何设置 _deviceName_deviceProperty 的值在启动组件时?我并不坚持将这些参数作为 class 属性,如果可以以不同的方式完成,我也很好。任何帮助表示赞赏。

由于您使用的是 JavaDSL,因此您只需在循环内定义 RouteDefinitions。只需确保每个 Route 定义都有唯一的 URI 和 RouteID。

示例(不编译):

public class ExampleRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        
        List<HashMap<String, String>> targets = createTargets();
        for (HashMap<String,String> target : targets) {
           configureRouteForTarget(target.get("name"), target.get("deviceName"), target.get("deviceProperty"));
        }
    }

    void configureRouteForTarget(String name, String deviceName, String deviceProperty){

        final String URI = "timer:"+ name + "?repeatCount=1";
        from(URI)
            .routeId(name+"TimerRoute")
            .setBody(constant(null))
            .setHeader(Exchange.CONTENT_TYPE, simple("text/event-stream"))
            .setHeader("CamelHttpMethod", simple("GET"))
            .to("https://myUrl/"
                + deviceName + "::" + deviceProperty //
                + "?disableStreamCache=true" //
            ) 
            .process(data -> {
                //... my process ...
            })
            .log("${body}")
            .to("direct:someEndpoint");
    }

    private List<HashMap<String, String>> createTargets() {

        List<HashMap<String, String>> targets = new ArrayList<HashMap<String,String>>();
        for (int i = 1; i <= 3; i++) {
            HashMap<String, String> map = new HashMap<>();
            map.put("name", "target" + i);
            map.put("deviceName", "device" + i);
            map.put("deviceProperty", "property" + i);
        }
        return targets;
    }
}