Apache Camel路由API调用消息队列

时间:2018-06-12 13:30:32

标签: rest apache-camel

我有两个使用REST API相互通信的应用程序。

我想知道我是否可以使用Apache Camel作为代理,可以坚持" API调用,例如将它们作为消息存储在ActiveMQ中,然后将请求路由到实际的API端点。

实际上,我想使用Apache Camel来增强" API端点添加持久性,限制请求等......

您建议使用哪个组件?

1 个答案:

答案 0 :(得分:1)

您始终可以尝试将HTTP请求桥接到队列中,但是可以通过将exchangePattern强制设置为InOut来使线程等待。

请参见以下示例:

2018-01-18T08:40:00+03:00

如果您正在使用maven,则这里是pom.xml:

import org.apache.activemq.broker.BrokerService;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Main {

    private static final Logger logger = LoggerFactory.getLogger(SimpleRouteBuilder.class);

    public static void main(String[] args) throws Exception {
        org.apache.camel.main.Main main = new org.apache.camel.main.Main();
        main.addRouteBuilder(new SimpleRouteBuilder());
        logger.info("Next call is blocking, ctrl-c to exit\n");
        main.run();
    }
}

class SimpleRouteBuilder extends RouteBuilder {

    private static final Logger logger = LoggerFactory.getLogger(SimpleRouteBuilder.class);

    public void configure() throws Exception {


        // launching an activemq in background
        final BrokerService broker = new BrokerService();
        broker.setBrokerName("activemq");
        broker.addConnector("tcp://localhost:61616");
        Runnable runnable = () -> {
            try {
                broker.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        runnable.run();

        // receiving http request but queuing them
        from("jetty:http://127.0.0.1:10000/input")
            .log(LoggingLevel.INFO, logger, "received request")
            .to("activemq:queue:persist?exchangePattern=InOut"); // InOut has to be forced with JMS

        // dequeuing and calling backend
        from("activemq:queue:persist")
            .log(LoggingLevel.INFO, logger,"requesting to destination")
            .removeHeaders("CamelHttp*")
            .setHeader("Cache-Control",constant("private, max-age=0,no-store"))
            .to("jetty:http://perdu.com?httpMethod=GET");
    }

}