首页 > 解决方案 > Apache Camel Rest 为发布请求发送响应

问题描述

我有一个骆驼端点,另一个应用程序发送一个带有一些数据的发布请求(也许有其他一些路由)

我想处理这些数据并通过 POST 请求的响应将某些内容返回给应用程序。

这就是我的骆驼上下文目前的样子:

 <camelContext xmlns="http://camel.apache.org/schema/blueprint">

    <restConfiguration component="restlet" bindingMode="json" port="8989" enableCORS="true"/>

    <rest path="/finData">
      <description>User rest service</description>
      <post>
        <to uri="direct:update"/>
      </post>
    </rest>

    <route id="sendFinData">
      <from uri="direct:update"/>
      <log message="Got some data:  ${body}"/>
      <to uri="aclient://otherClient"/>
    </route>

  </camelContext>

如何通过发布请求的响应从路由 sendFinData 发回一些答案?

标签: restapache-camelcamel-rest

解决方案


对您的路线的发布请求收到的响应是路线末尾的 ${body} 中的任何内容。

因此,在您的路线结束时, ${body} 包含来自的响应

<to uri="aclient://otherClient"/>

我不使用 Camel XML,但在 Java 中你会这样做:

    rest("/finData")
        .get()
        .route()
        .to("direct:sendFindData")
        .end();

    from("direct:sendFindData")
        .to("aclient://otherClient")
        .process(exchange -> exchange.getIn().setBody("Hello world"))
        .setBody(simple("GoodBye world")) // same thing as line above
        .end();

如果您要传回给请求者的数据不是您路由中最后一次 API 调用的响应,您需要将其临时保存在某处(exchange.properties)并稍后将其设置回正文,或聚合响应以便原始数据不会被覆盖。路由应该产生消费者期望的数据。对于正常的休息请求,这应该是字符串类型(如“GoodBye world”)。例如,如果要返回 JSON,请确保响应正文是路径末尾的 JSON 字符串。

抱歉,我无法为 XML 提供帮助,但希望这对您有所帮助。


推荐阅读