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


Posted in Servers onJune 10, 2022

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

<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() + "}");
			}
		});
		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。

<dependencyManagement>
		<dependencies>
			<!-- Spring Boot BOM -->
			<dependency>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>${spring-boot.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<!-- Camel BOM -->
			<dependency>
				<groupId>org.apache.camel.springboot</groupId>
				<artifactId>camel-spring-boot-dependencies</artifactId>
				<version>${camel.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
			<dependency>
				<groupId>org.projectlombok</groupId>
				<artifactId>lombok</artifactId>
				<version>1.18.20</version>
				<scope>provided</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
			<exclusions>
				<exclusion>
					<groupId>com.fasterxml.jackson.datatype</groupId>
					<artifactId>jackson-datatype-jsr310</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.fasterxml.jackson.core</groupId>
					<artifactId>jackson-annotations</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>com.fasterxml.jackson.datatype</groupId>
					<artifactId>jackson-datatype-jsr310</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.camel.springboot</groupId>
			<artifactId>camel-spring-boot-starter</artifactId>

		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.camel.springboot</groupId>
			<artifactId>camel-jackson-starter</artifactId>
			<exclusions>
				<exclusion>
					<groupId>com.fasterxml.jackson.core</groupId>
					<artifactId>jackson-annotations</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.camel.springboot</groupId>
			<artifactId>camel-servlet-starter</artifactId>
		</dependency>
		<!-- Testing Dependencies -->
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-test-spring</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>com.vaadin.external.google</groupId>
					<artifactId>android-json</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-swagger-java</artifactId>

		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-bean-validator</artifactId>
		</dependency>
	</dependencies>

总结

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

到此这篇关于使用Apache Camel表达REST服务的方法的文章就介绍到这了!


Tags in this post...

Servers 相关文章推荐
使用Apache的rewrite
Mar 09 Servers
为什么 Nginx 比 Apache 更牛逼
Mar 31 Servers
Linux安装Nginx步骤详解
Mar 31 Servers
JVM上高性能数据格式库包Apache Arrow入门和架构详解(Gkatziouras)
May 26 Servers
制作能在nginx和IIS中使用的ssl证书
Jun 21 Servers
使用 Apache 反向代理的设置技巧
Jan 18 Servers
Tomcat项目启动失败的原因和解决办法
Apr 20 Servers
Ubuntu安装Mysql+启用远程连接的完整过程
Jun 21 Servers
Windows Server 修改远程桌面端口的实现
Jun 25 Servers
VMware虚拟机安装 Windows Server 2022的详细图文教程
Sep 23 Servers
ubuntu端向日葵键盘输入卡顿问题及解决
Dec 24 Servers
CentOS7环境下MySQL8常用命令小结
Jun 10 #Servers
CentOS7安装MySQL8的超级详细教程(无坑!)
ubuntu下常用apt命令介绍
Jun 05 #Servers
netty 实现tomcat的示例代码
Jun 05 #Servers
基于docker安装zabbix的详细教程
Jun 05 #Servers
linux目录管理方法介绍
Jun 01 #Servers
Linux磁盘管理方法介绍
Jun 01 #Servers
You might like
计算一段日期内的周末天数的php代码(星期六,星期日总和)
2009/11/12 PHP
php表单转换textarea换行符的方法
2010/09/10 PHP
那些年一起学习的PHP(二)
2012/03/21 PHP
php用ini_get获取php.ini里变量值的方法
2015/03/04 PHP
PHP实现补齐关闭的HTML标签
2016/03/22 PHP
CI框架整合smarty步骤详解
2016/05/19 PHP
prototype 源码中文说明之 prototype.js
2006/09/22 Javascript
通过event对象的fromElement属性解决热区设置主实体的一个bug
2008/12/22 Javascript
window.ActiveXObject使用说明
2010/11/08 Javascript
Tab页界面 用jQuery及Ajax技术实现(php后台)
2011/10/12 Javascript
js设置cookie过期及清除浏览器对应名称的cookie
2013/10/24 Javascript
JavaScript判断数组是否包含指定元素的方法
2015/07/01 Javascript
利用jQuery解析获取JSON数据
2017/04/08 jQuery
Angular4学习之Angular CLI的安装与使用教程
2018/01/04 Javascript
老生常谈JavaScript获取CSS样式的方法(兼容各浏览器)
2018/09/19 Javascript
Vue 2.0 侦听器 watch属性代码详解
2019/06/19 Javascript
vue中解决微信html5原生ios虚拟键返回不刷新问题
2020/10/20 Javascript
[05:20]卡尔工作室_DOTA2新手教学_DOTA2超强新手功能
2013/04/22 DOTA
[03:42]2014DOTA2西雅图国际邀请赛 Navi战队巡礼
2014/07/07 DOTA
[05:36]DOTA2 2015国际邀请赛中国区预选赛第四日TOP10
2015/05/29 DOTA
[33:42]LGD vs OG 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
python中 ? : 三元表达式的使用介绍
2013/10/09 Python
Windows8下安装Python的BeautifulSoup
2015/01/22 Python
jupyter安装小结
2016/03/13 Python
Python将图片批量从png格式转换至WebP格式
2020/08/22 Python
通过源码分析Python中的切片赋值
2017/05/08 Python
Python+Socket实现基于TCP协议的客户与服务端中文自动回复聊天功能示例
2017/08/31 Python
python numpy和list查询其中某个数的个数及定位方法
2018/06/27 Python
Python远程视频监控程序的实例代码
2019/05/05 Python
Django中如何使用sass的方法步骤
2019/07/09 Python
Python利用逻辑回归模型解决MNIST手写数字识别问题详解
2020/01/14 Python
PyQt5.6+pycharm配置以及pyinstaller生成exe(小白教程)
2020/06/02 Python
Python如何使用ElementTree解析xml
2020/10/12 Python
如何通过Python实现RabbitMQ延迟队列
2020/11/28 Python
C++和python实现阿姆斯特朗数字查找实例代码
2020/12/07 Python
python selenium 获取接口数据的实现
2020/12/07 Python