带有处理器的 Apache Camel Rest Route

问题描述 投票:0回答:1

我是 Apache Camel 的新手,一直在努力为 REST 端点定义路由,我打算在其中接受请求、执行一些过滤和处理并返回响应。下面是我的示例代码,它不起作用,我做错了什么? 是否有示例/文档可供我实现类似的事情,即在请求验证失败等情况下使用失败响应代码进行响应?

public class RestRoute extends RouteBuilder {

  public static final String DIRECT_HELLO = "direct:hello";

  private final UpperCaseProcessor upperCaseProcessor;

  public RestRoute(UpperCaseProcessor upperCaseProcessor) {
    this.upperCaseProcessor = upperCaseProcessor;
  }

  @Override
  public void configure() throws Exception {
    rest("/myapp")
        .get("/hello").param().dataType("string").name("name").endParam().to(DIRECT_HELLO);

    from(DIRECT_HELLO)
        .tracing()
        .filter(exchange -> exchange.getIn().getBody() instanceof String)
        .process(upperCaseProcessor)
        .setHeaders(Exchange.HTTP_RESPONSE_CODE, constant(200));

  }
}
apache-camel
1个回答
0
投票

在 Apache Camel 路由定义中,需要进行一些调整和澄清才能使其正常运行,特别是处理 REST 请求、处理和使用适当的 HTTP 状态代码进行响应。

设置HTTP响应代码:

  • 您当前设置 HTTP 响应代码的方法未正确实现。你应该使用exchange.getMessage().setHeader而不是setHeaders。

过滤和处理:

  • 您的过滤逻辑检查主体是否是 String 的实例。这很好,但请确保您的处理器 (UpperCaseProcessor) 已正确实现以处理预期的操作。

  • 如果您想在请求验证失败时(例如,当正文不是字符串时)响应失败状态代码,您需要显式处理此问题。

回复:

  • 处理后,您应该将消息正文设置为您想要作为响应返回的内容。
public class RestRoute extends RouteBuilder {

  public static final String DIRECT_HELLO = "direct:hello";

  private final UpperCaseProcessor upperCaseProcessor;

  public RestRoute(UpperCaseProcessor upperCaseProcessor) {
    this.upperCaseProcessor = upperCaseProcessor;
  }

  @Override
  public void configure() {
    rest("/myapp")
        .get("/hello")
          .param().dataType("string").name("name").endParam()
          .to(DIRECT_HELLO);

    from(DIRECT_HELLO)
        .tracing()
        .filter().method(exchange -> {
            // Check if the body is a String, otherwise set a failure response code
            if (!(exchange.getIn().getBody() instanceof String)) {
                exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400)); // Bad Request
                exchange.getMessage().setBody("Invalid request");
                return false; // Stop processing
            }
            return true; // Continue processing
        })
        .process(upperCaseProcessor)
        .choice()
            .when(header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(400))
                .stop() // Stop routing for bad requests
            .otherwise()
                .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(200)) // Set success status code
                .endChoice();
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.