我是 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 入门: 开始使用 https://camel.apache.org/camel-core/getting-started/
Apache Camel 文档: https://camel.apache.org/manual/latest/index.html
REST DSL 指南: 这部分专门讨论使用 Apache Camel 设置 REST 服务:https://camel.apache.org/manual/latest/rest-dsl.html
ErrorHandler:https://camel.apache.org/manual/error-handler.html
在 Apache Camel 路由定义中,需要进行一些调整和澄清才能使其正常运行,特别是处理 REST 请求、处理和使用适当的 HTTP 状态代码进行响应。
设置HTTP响应代码:
过滤和处理:
您的过滤逻辑检查主体是否是 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();
}
}