Spring Boot Camel Route-从其余端点获取数据

时间:2019-03-22 12:35:26

标签: spring spring-boot apache-camel spring-camel

我想在Spring Boot(2.1.1)项目中创建骆驼路线,以从某个(其余)端点(http://localhost:8080/getAllUsers)获取数据并将其发送到activeMq。

我尝试使用计时器数据在activeMq上发送它并使用它,并且它正在工作。但是我从端点收集数据时遇到问题。

我尝试了几件事,但没有成功。这就是我尝试过的。

在此示例中,我没有将数据发送到ActiveMq,我只想查看响应...

public void createNewRoute() {
CamelContext context = new DefaultCamelContext();

try {
  ProducerTemplate template = context.createProducerTemplate();
  context.start();

  Exchange exchange = template.request("http://localhost:8080/getAllUsers",
      new Processor() {
        public void process(Exchange exchange) throws Exception {
        }
      });

  if (null != exchange) {
    Message out = exchange.getOut();
    int responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
    System.out.println("Response: " + String.valueOf(responseCode));
  }

  Thread.sleep(1000 * 3);
  context.stop();
} catch (Exception ex) {
  System.out.println("Exception: " + ex);
}

System.out.println("DONE!!");
 }

另一条路线:

 from("servlet://localhost:8080/getAllUsers").to("activemq://all-users");

另一个:

 rest("//localhost:8080/getAllUsers")
 .get().consumes("application/json")
 .to("activemq://all-users");

3 个答案:

答案 0 :(得分:1)

不使用context.start()尝试此操作。

   CamelContext camelContext = new DefaultCamelContext();
    ProducerTemplate template = camelContext.createProducerTemplate();

    Exchange exchange = template.send("http://localhost:8080/getAllUsers", new Processor() {
        public void process(Exchange exchange) throws Exception {}
    });

    Message out = exchange.getOut();   

答案 1 :(得分:1)

http组件基于流,因此您可以要求Camel以字符串形式返回响应。

String s = exchange.getMessage().getBody(String.class);

在这些链接中查看更多

答案 2 :(得分:1)

我将继续讲第二个例子:

from("timer://test?repeatCount=1").routeId("newRoute")
    .streamCaching()
    .process(exchange -> exchange.getIn()
        .setBody(exchange.getIn()
            .getBody()))
    .marshal()
    .json(JsonLibrary.Jackson)
    .setHeader(Exchange.HTTP_METHOD, constant("GET"))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .to("http://localhost:8080/getAllUsers")
    .log(LoggingLevel.INFO, "This is my body: ${body}")
    .to("activemq:queue://new-queue");

这将触发一次。