加入收藏 | 设为首页 | 会员中心 | 我要投稿 甘南站长网 (https://www.0941zz.com/)- 科技、行业物联网、开发、云计算、云管理!
当前位置: 首页 > 运营中心 > Apache > 正文

使用Apache Camel表达REST服务的方式

发布时间:2023-02-20 10:53:27 所属栏目:Apache 来源:互联网
导读:使用Apache Camel的REST服务 Apache Camel可以作为一个独立的或嵌入的库在任何地方运行,它可以帮助整合。继续阅读,了解如何使用它来暴露REST服务。 如何使用Apache Camel来表达REST服务 Camel REST允许使用Restlet、Servlet和许多这样的HTTP感知组件来实现
  使用Apache Camel的REST服务
  Apache Camel可以作为一个独立的或嵌入的库在任何地方运行,它可以帮助整合。继续阅读,了解如何使用它来暴露REST服务。
 
  如何使用Apache Camel来表达REST服务
  Camel REST允许使用Restlet、Servlet和许多这样的HTTP感知组件来实现REST服务的创建。
 
  大家都知道,Camel的主要功能是路由引擎。路由可以使用基于Java的DSL或基于XML来开发。在这篇文章中,我将按照JavaDSL来开发一个REST服务。
 
 
  定义端点
  为了定义端点,我们需要使用Apache Camel DSL与 Java DSL(尽管你可以使用XML)。
 
  下面是Java DSL。

  rest("/api/products")
       .get().route().to("...")
       .post().route().to("...")
       .delete().route().to("...");
  它与Camel路由类似,但使用rest() 。我们需要提到用于暴露端点的组件服务。Camel支持以下组件来实现Bootstrap REST服务。
 
  Servlet
  Spark REST
  Netty HTTP
  Jetty
  如果你打算将Camel与Spring Boot框架集成以暴露服务,最好使用servlet 组件,因为Spring Boot支持嵌入式Tomcat,Camel可以使用它。
 
  让我们把REST配置成。

  // Define the implementing component - and accept the default host and port
  restConfiguration()
    .component("servlet");
 
  如何覆盖端口
  你可以用你选择的任何其他端口号来覆盖默认的8080端口,方法是将.port() 设置为restConfiguration() API,或者,如果你将Apache Camel与Spring Boot集成,你可以使用application.properties 中的server.port=8082 。
 
 
  覆盖上下文路径
  默认情况下,Camel将导入请求映射到/camel/* 。你可以通过使用application.properties 作为camel.component.servlet.mapping.context-path=/services/api/*,将其覆盖到你选择的任何特定路径。
 
  配置绑定模式,将请求集合到POJO对象。如果设置为 "off "以外的任何内容,生产者将尝试把传入信息的主体从inType转换为JSON或XML,而把响应从JSON或XML转换为outType。有五个枚举,其值可以是以下之一:自动、关闭、JSON、XML或json_xml。为了实现这一点,你需要将绑定模式设置为restConfiguration() ,因为bindingMode(RestBindingMode.auto); 。
 
  请看下面的REST API的配置样本。

  @Component
  public class HttpRouteBuilder extends BaseRouteBuilder {
      @Override
      public void configure() throws Exception {
          super.configure();
          // it tells Camel how to configure the REST service
          restConfiguration()
                  // Use the 'servlet' component.
                  // This tells Camel to create and use a Servlet to 'host' the RESTful API.
                  // Since we're using Spring Boot, the default servlet container is Tomcat.
                  .component("servlet")
                  // Allow Camel to try to marshal/unmarshal between Java objects and JSON
                  .bindingMode(RestBindingMode.auto);
  
          rest().get("/kyc/{uid}").route().process("httpRequestProcessor").to("log:?level=INFO&showBody=true").endRest();
  
          rest().post("/kyc").type(RequestObject.class).route().to("bean-validator:myvalidatorname")
                  .process("httpRequestProcessor").to("log:?level=INFO&showBody=true");
      }
  }
  您可以使用Apache Camel bean验证器组件验证传入的请求,这需要在您的Maven POM中添加camel-bean-validator 依赖关系。
 
  <dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-bean-validator</artifactId>
  </dependency>
 
  在请求对象中定义验证规则
  为了实现输入请求验证,你需要为POJO/请求类中的字段添加验证注解。这些注释可在包javax.validation.constraints 。JSR-303 API中最常见的是。
 
  @NotNull - 检查该字段是否是null
  @AssertTrue/@AssertFalse - 检查该字段是否为真或假
  @Pattern(regex=, flags=) - 检查该字段是否与给定的 ,与给定的regex flags
  在org.hibernate.validator.constraints ,有一些Hibernate特有的注释,比如。
 
  @Email - 检查该字段是否包含一个有效的电子邮件地址
  @CreditCardNumber - 这个可能很明显
  @NotEmpty - 检查注解的字段是否为空或空。
 
  如何处理异常
  你可以处理不同类型的异常,并使用Apache Camel异常条款(onException )向客户端发送自定义的错误信息,无论是在路由级别还是在全球级别。你也可以重写REST API调用的HTTP响应代码和消息。
 
  public class BaseRouteBuilder extends RouteBuilder {
      @Override
      public void configure() throws Exception {
          onException(BeanValidationException.class).handled(true).process(new Processor() {
              @Override
              public void process(Exchange exchange) throws Exception {
                  Throwable cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
                  exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 400);
                  exchange.getMessage().setHeader(Exchange.CONTENT_TYPE, MediaType.APPLICATION_JSON);
                  exchange.getMessage().setBody("{error:" + cause.getMessage() + "}");
              }
          });
          onException(InvalidRequestException.class).handled(true).process(new Processor() {
              @Override
              public void process(Exchange exchange) throws Exception {
                  Throwable cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
                  exchange.getMessage().setHeader(Exchange.HTTP_RESPONSE_CODE, 400);
                  exchange.getMessage().setHeader(Exchange.CONTENT_TYPE, MediaType.APPLICATION_JSON);
                  exchange.getMessage().setBody("{error:" + cause.getMessage() + "}");
              }

(编辑:甘南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读