从 REST 控制器调用 Apache Camel 路由

Calling Apache Camel route from a REST controller

我有一份看起来像这样的工作:

@Named
public class MyCamelRouteBuilder extends RouteBuilder {

    private static final String JOB_NAME = "abc";
    private static final String JOB_METHOD_NAME = "xyz";

    private final MyJob myJob;

    @Inject
    public MyCamelRouteBuilder(MyJob myJob) {
        super();
        this.myJob = myJob;
    }

    @Override
    public void configure() {
        fromF("direct:%s", JOB_NAME)
            .routeId(JOB_NAME)
            .bean(myJob, JOB_METHOD_NAME)
            .end();

        fromF("master:some_name_1/some_name_2:scheduler:%s?delay=%s", JOB_NAME, 1234)
            .routeId("JobTimer")
            .toF("direct:%s", JOB_NAME)
            .end();
    }
}

作业的一个非常简化的版本class:

@Named
public class MyJob {

    private MyJob() {}
    }

    public void xyz() {

    }
}

这确实有效,并且确实按预期触发了。

问题从这里开始:

现在,我还想创建一个能够触发完全相同作业的 REST 控制器。像这样:

@Named
@RestController
@RequestMapping
@Validated
public class MyController {

    private static final String JOB_NAME = "abc";

    private final ProducerTemplate producerTemplate;

    @Inject
    public MyController(
            ProducerTemplate producerTemplate
    ) {

        this.producerTemplate = producerTemplate;
    }

    @PostMapping(path = "/my_endpoint")
    public String run() throws Exception {
        producerTemplate.requestBody("direct:" + JOB_NAME);
        return "ok";
    }
}

但是一旦到达这一行,作业就不会被触发并且请求调用一直挂起。

producerTemplate.requestBody("direct:" + JOB_NAME);

有什么想法吗?

我的问题的解决方案:

@Named
@RestController
@RequestMapping
@Validated
public class MyController {
    private static final String JOB_NAME = "abc";

    @Produce("direct:" + JOB_NAME)
    private final ProducerTemplate producerTemplate;
    private final CamelContext context;

    @Inject
    public MyController(
            ProducerTemplate producerTemplate, CamelContext context
    ) {
        this.producerTemplate = producerTemplate;
        this.context = context;
    }

    @PostMapping(path = "/my_endpoint")
    public String run() throws Exception {

        Exchange exchange = new DefaultExchange(context);
        producerTemplate.send(exchange);

        return "ok";
    }
}