欢迎来到站长天空!

其它服务器

当前位置: 主页 > 服务器 > 其它服务器

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

时间:2025-12-23 07:30:03|栏目:其它服务器|点击:

目录
  • 使用Apache Camel的REST服务
    • 如何使用Apache Camel来表达REST服务
      • 定义端点
      • 如何覆盖端口
      • 覆盖上下文路径
      • 在请求对象中定义验证规则
      • 如何处理异常
    • 总结

    使用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。

    Java

    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配置成。

    Java

    // 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 依赖关系。

    
      org.apache.camel
      camel-bean-validator
    

    在请求对象中定义验证规则

    为了实现输入请求验证,你需要为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() + "}");
    			}
    		});
    		onException(Exception.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, 500);
    				exchange.getMessage().setHeader(Exchange.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    				exchange.getMessage().setBody("{error:" + cause.getMessage() + "}");
    			}
    		});
    }

    注意:在这里我创建了一个基类来处理各种异常,在我的主REST API构建器类(HttpRouteBuilder)中,它扩展了BaseRouteBuilder

    最后是POM。

    
    		
    			
    			
    				org.springframework.boot
    				spring-boot-dependencies
    				${spring-boot.version}
    				pom
    				import
    			
    			
    			
    				org.apache.camel.springboot
    				camel-spring-boot-dependencies
    				${camel.version}
    				pom
    				import
    			
    			
    				org.projectlombok
    				lombok
    				1.18.20
    				provided
    			
    		
    	
    
    	
    		
    			org.springframework.boot
    			spring-boot-starter-actuator
    			
    				
    					com.fasterxml.jackson.datatype
    					jackson-datatype-jsr310
    				
    				
    					com.fasterxml.jackson.core
    					jackson-annotations
    				
    			
    		
    		
    			org.springframework.boot
    			spring-boot-starter-web
    			
    				
    					com.fasterxml.jackson.datatype
    					jackson-datatype-jsr310
    				
    			
    		
    		
    			org.apache.camel.springboot
    			camel-spring-boot-starter
    
    		
    
    		
    			org.projectlombok
    			lombok
    			true
    		
    		
    			org.springframework.boot
    			spring-boot-starter-test
    			test
    		
    		
    			org.apache.camel.springboot
    			camel-jackson-starter
    			
    				
    					com.fasterxml.jackson.core
    					jackson-annotations
    				
    			
    		
    		
    			org.apache.camel.springboot
    			camel-servlet-starter
    		
    		
    		
    			org.apache.camel
    			camel-test-spring
    			test
    		
    		
    			org.springframework.boot
    			spring-boot-starter-test
    			test
    			
    				
    					com.vaadin.external.google
    					android-json
    				
    			
    		
    		
    			org.apache.camel
    			camel-swagger-java
    
    		
    		
    			org.apache.camel
    			camel-bean-validator
    		
    	

    总结

    现在你知道了如何用Camel暴露REST API,你可能想知道什么时候/为什么要用Apache Camel来构建REST服务。简单的答案是,如果你已经在使用Apache Camel来整合不同协议和应用程序之间的数据,那么REST是你需要支持的另一个数据源,而不是用Spring Boot或任何其他框架来构建REST服务。你可以利用Camel REST组件来暴露REST API,并使用已知的Camel DSL来消费/生产消息,这有助于你规范技术桩。你还可以扩展Camel REST,使其包括Swagger,以便使用camel-swagger 组件提供API规范。

    上一篇:nginx配置防盗链的三种实现方式总结

    栏    目:其它服务器

    下一篇:Nginx开源可视化配置工具NginxConfig使用教程

    本文标题:使用Apache Camel表达REST服务的方法

    本文地址:https://zz.feitang.co/server/32858.html

    广告投放 | 联系我们 | 版权申明

    申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

    如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

    联系QQ:257218569 | 邮箱:257218569@qq.com

    Copyright © 2018-2025 站长天空 版权所有 Powered by EyouCms冀ICP备14023439号