从REST控制器调用Apache Camel路由

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

我有一个类似这样的工作:

@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();
    }
}

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

@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);

有什么想法吗?

hrysbysz

hrysbysz1#

我的问题的解决方法:

@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";
    }
}

相关问题