Apache Camel
- 格式:doc
- 大小:426.50 KB
- 文档页数:27
Camel-应用开发文档版本 1.0修订记录目录修订记录 (2)1.前言 (5)1.1.本手册 (5)1.2.阅读范围 (5)1.3.名称解释 (5)2.背景 (5)3.需求概要 (5)4.Apache Camel (6)4.1.概述 (6)4.2.本文档所在版本 (6)4.3.使用场景 (6)4.4.架构 (7)4.5.关键术语&类 (8)4.6.Camel消息转换 (9)4.6.1.消息路由 (9)4.6.2.消息转换 (10)5.应用集成 (10)5.1.依赖 (11)5.1.1.maven项目 (11)5.1.2.gradle项目 (11)5.2.配置 (12)5.2.1.Camel配置文件 (12)5.2.2.Spring集成 (12)5.3.应用开发 (13)5.3.1.定义Endpoint (13)5.3.2.消息处理 (14)5.3.3.启动CamelContext (15)6.附录 (16)6.1.参考文档 (16)6.2.其它 (17)1.前言1.1.本手册本文档对Camel在业务系统的应用开发进行说明,对该技术使用场景,所涉及到技术架构,技术要点,集成开发作出详细说明,对该核技术可扩展性、稳定性、安全性进行阐述、对该技术在未来发展进行评估,供开发时参考。
1.2.阅读范围技术相关人员,包括技术总监,开发主管,开发工程师。
1.3.名称解释2.背景3.需求概要针对外部业务,需要e-码头以最少代价,应付不断变化的业务需求;e-码头所涉及的物流服务业务,跨公司,跨机构,跨部门,外部对接了电商,物流,国检,海关业务和系统,特别是海关业务和所对接系统正值发展期,在目前,已经对接的业务,是经过不断变化形成的,未来,还会出现未知的,不断发展变化业务需求。
针对这种自动化完成,带有很强的业务执行顺序和业务流程特性,需要一种,能够打破跨机构跨部门跨业务,管理既定工作的流程,精准控制服务编排的应用技术,来统一调整和控制各个业务执行过程,在e-码头项目引入Activiti BPM Platform(以下简称Activiti)。
camel 表达式使用Camel表达式是一种用于数据转换和路由的领域特定语言。
它被广泛应用于集成框架Apache Camel中,用于处理消息和数据的传输和转换。
本文将介绍Camel表达式的基本语法和用法,并通过具体示例来说明其实际应用。
我们来了解一下Camel表达式的基本语法。
Camel表达式由一系列的关键字和操作符组成,用于指定数据的来源、转换和目标。
其中,关键字表示不同的操作,操作符用于连接关键字和操作数。
Camel 表达式支持多种数据类型,包括字符串、数字、日期等。
在Camel表达式中,可以使用变量来引用数据,变量以"$"符号开头。
例如,"$body"表示消息的主体内容,"$header.xxx"表示消息头的属性值,"$exchange"表示消息的交换对象等。
通过使用这些变量,我们可以灵活地访问和操作消息的各个部分。
除了使用变量,Camel表达式还支持一些常用的函数和操作符,用于对数据进行计算和转换。
例如,"toUpperCase()"函数用于将字符串转换为大写形式,"length()"函数用于计算字符串的长度,"+ - * /"等操作符用于进行数值计算等。
通过组合使用这些函数和操作符,我们可以实现复杂的数据处理逻辑。
接下来,我们通过一个具体的示例来说明Camel表达式的实际应用。
假设我们有一个消息队列,其中包含了一些订单信息。
我们需要根据订单的金额来判断订单的类型,并将订单分发到不同的处理节点上。
为了实现这个功能,我们可以使用Camel表达式来进行条件判断和路由。
我们需要定义一个路由规则,用于根据订单金额进行条件判断。
假设订单金额大于1000的为大额订单,小于等于1000的为普通订单。
我们可以使用如下的Camel表达式来实现:```.choice().when().simple("${body.amount} > 1000").to("direct:bigOrder").otherwise().to("direct:normalOrder").end()```在上述表达式中,".choice()"关键字表示进行条件判断,".when()"关键字后面的表达式表示条件判断的条件,".to()"关键字后面的表达式表示条件满足时的处理逻辑,".otherwise()"关键字后面的表达式表示条件不满足时的处理逻辑。
ApacheCamel框架原理与使用Apache Camel框架原理与使用Apache Camel是一个开源的集成框架,用于实现企业应用程序之间的消息路由、转换、路由、集成和扩展。
它提供了一组易于使用的API和组件,以及丰富的企业级模式,可以帮助开发人员更加轻松地构建各种集成解决方案。
一、Apache Camel框架的基本原理Apache Camel框架基于企业集成模式(Enterprise Integration Patterns)的思想,通过使用一组已定义的组件和路由规则,将不同的应用程序和系统连接在一起。
下面是Apache Camel框架的基本原理:1. 组件:Apache Camel框架提供了一套丰富的组件,用于与不同的系统和技术进行交互,如File、HTTP、JMS等。
开发人员可以基于自己的需求选择合适的组件,以实现与特定系统的集成。
2. 路由:路由是Apache Camel框架的核心概念之一,它定义了消息从一个端点(endpoint)到另一个端点的路径。
开发人员可以使用各种路由规则,如条件判断、循环等,来定义不同场景下消息的路由逻辑。
3. 转换:Apache Camel框架支持多种消息格式和协议,开发人员可以使用转换器来实现消息的转换。
框架内置了许多常用的转换器,同时也支持自定义转换器。
4. 调度:Apache Camel框架提供了调度器组件,可以按照预定的时间间隔或特定的时间点执行任务。
这对于定时发送或处理消息非常有用。
5. 错误处理:Apache Camel框架有强大的错误处理机制,可以处理路由中的异常情况。
开发人员可以根据具体需求定义错误处理策略,如重试、跳过、终止等。
二、Apache Camel框架的使用使用Apache Camel框架可以通过以下几个步骤来完成:1. 引入依赖:在你的项目中引入Apache Camel框架的相关依赖。
你可以通过Maven或Gradle等构建工具来管理依赖。
⼏款开源的ETL⼯具介绍ETL,是英⽂ Extract-Transform-Load 的缩写,⽤来描述将数据从来源端经过抽取(extract)、转换(transform)、加载(load)⾄⽬的端的过程。
ETL 是构建数据仓库的重要⼀环,⽤户从数据源抽取出所需的数据,经过数据清洗,最终按照预先定义好的数据仓库模型,将数据加载到数据仓库中去。
我们在下⽅列出了 7 款开源的 ETL ⼯具,并讨论了从 ETL 转向“⽆ ETL”的过程,因为 ELT 正迅速成为现代数据和云环境的终极过程。
注:原⽂包含 11 项 ETL ⼯具,本⽂提取了其中开源的 7 项,另增加了⼀款使⽤普遍的 Kettle,如需对另外 4 项进⾏了解,可点击⽂末链接进⾏查看。
优秀的 ETL ⼯具1、Apache CamelApache Camel 是⼀个⾮常强⼤的基于规则的路由以及媒介引擎,该引擎提供了⼀个基于 POJO 的企业应⽤模式(Enterprise Integration Patterns)的实现,你可以采⽤其异常强⼤且⼗分易⽤的 API (可以说是⼀种 Java 的领域定义语⾔ Domain Specific Language)来配置其路由或者中介的规则。
通过这种领域定义语⾔,你可以在你的 IDE 中⽤简单的 Java Code 就可以写出⼀个类型安全并具有⼀定智能的规则描述⽂件。
2、Apache KafkaApache Kafka 是⼀个开源的消息系统,⽤ Scala 和 Java 写成。
该项⽬为处理实时数据提供了⼀个统⼀、⾼通量、低延时的平台。
有如下特性:通过 O(1) 的磁盘数据结构提供消息的持久化,这种结构对于即使数以TB的消息存储也能够保持长时间的稳定性能。
⾼吞吐量:即使是⾮常普通的硬件 kafka 也可以⽀持每秒数⼗万的消息。
⽀持通过 kafka 服务器和消费机集群来分区消息。
⽀持 Hadoop 并⾏数据加载。
Camel运⾏原理分析Camel运⾏原理分析以⼀个简单的例⼦说明⼀下camel的运⾏原理,例⼦本⾝很简单,⽬的就是将⼀个⽬录下的⽂件搬运到另⼀个⽂件夹,处理器只是将⽂件(限于⽂本⽂件)的内容打印到控制台,⾸先代码如下:public static void main(String[] args) throws Exception {//创建Camel上下⽂DefaultCamelContext camelContext = new DefaultCamelContext();//添加⼀个路由,参数为路由建造者camelContext.addRoutes(new RouteBuilder() {@Overridepublic void configure() throws Exception {this.from("file:D:/temp/in").process(new Processor() {@Overridepublic void process(Exchange exchange) throws Exception {GenericFile<File> gf = exchange.getIn().getBody(GenericFile.class);File file = gf.getFile();PrintStream ps = new PrintStream(System.out);BufferedReader br =new BufferedReader(new InputStreamReader(new FileInputStream(file)));String line = null;while((line=br.readLine())!=null) {ps.println(line);}ps.close();br.close();}}).to("file:D:/temp/out");}});//启动上下⽂camelContext.start();//防⽌主线程退出Object object = new Object();synchronized (object) {object.wait();}}对于camel来说,其原理核⼼的部分主要包含路由信息的构建、组件查找、和路由启动过程三⽅⾯,下⾯结合以上简单例⼦对三个⽅⾯来对camel的源码进⾏分析:⼀、路由的构建其实这⾥说的路由构建其实是构建路由定义,对应Camel中的RouteDefinition类,⼀个RouteDefinition对象规定了或者说指定了⼀个消息从哪⾥产⽣,中间要经过什么样的处理,最后路由到什么地⽅。
Apache常用模块和参数1Apache服务配置指令1.1基本配置命令AccessFileName语法AccessFileName filename默认值AccessFileName .htaccess作用域server config, virtual host此命令是针对目录的访问控制文件的名称;AddDefaultCharset语法AddDefaultCharset On|Off|charset默认值AddDefaultCharset Off作用域server config, virtual host, directory, .htaccess用于指定默认的字符集,在HTTP的回应信息中,若在HTTP头中未包含任何关于内容字符集类型的参数时,此指令指定的字符集添加到HTTP头中,此时将覆盖网页文件中通过META 标记符所指定的字符集.默认字符集为: AddDefaultCharset UTF-8 若显示中文时出现乱码,解决方法是将字符集设置为GB2312,即: AddDefaultCharset GB2312DefaultType语法DefaultType MIME-type默认值DefaultType text/plain作用域server config, virtual host, directory, .htaccess服务器不知道文件类型时,用缺省值通知客户端;DocumentRoot设置Apache提供文件服务的目录;ErrorDocument设置当有问题发生时,Apache所做的反应;ForceType此指令强制所有匹配的文件被当作在MIME-type中指定的Content-Type来伺服。
比如说,如果您有一个包含大量GIF文件的目录,可您又不想全都为它们加上".gif"扩展名的话,您可以这样做:型的扩展名。
你可以通过使用"None"覆盖任何ForceType设置:<IfModule>使用不包含在Apache安装中的模块的命令Include包含其它的配置文件Listen默认值:80Listen命令告诉服务器接受来自指定端口或者指定地址的某端口的请求,如果listen仅指定了端口,则服务器会监听本机的所有地址;如果指定了地址和端口,则服务器只监听来自该地址和端口的请求Options控制某个特定目录所能使用的服务器功能;其值有:None:表示只能浏览,FollowSymLinks:允许页面连接到别处,ExecCGI:允许执行CGI,MultiViews:允许看动画或是听音乐之类的操作,Indexes:允许服务器返回目录的格式化列表,Includes:允许使用SSI。
ApacheCamel集成框架原理剖析Apache Camel集成框架原理剖析Apache Camel 是一个开源的企业级集成框架,它旨在简化应用程序之间的消息传递和通信。
本文将深入探讨Apache Camel的原理和机制,帮助读者更好地理解和使用这个强大的集成框架。
一、简介Apache Camel是一个基于企业集成模式(Enterprise Integration Patterns)的开源框架。
它提供了一个优雅的、简化的方式来连接不同的应用和系统,通过消息传递和路由来实现各种集成场景。
二、核心概念1. 路由(Route)在Apache Camel中,路由是最基本的概念。
它代表了一条从起始点到目的地的路径,可以包含多个环节。
每个环节都定义了消息的处理逻辑,可以进行转换、过滤、聚合等操作。
2. 组件(Component)组件是Apache Camel的基本构建块,用于与系统和应用程序进行通信。
它们负责消息的接收和发送,包括连接协议、数据格式转换等功能。
Apache Camel提供了丰富的组件,如HTTP、JMS、FTP等,同时也支持自定义组件。
3. 路由器(Router)路由器是Apache Camel中定义路由逻辑的组件。
它负责将消息从一个组件传递到另一个组件,根据配置的规则进行路由和转换。
路由器可以根据消息内容、标头、路由策略等条件进行决策,以确保消息的正确路由和处理。
4. 转换器(Transformer)转换器是Apache Camel中用于消息转换的组件。
它负责将消息从一个格式转换为另一个格式,以满足系统和应用程序的需求。
Apache Camel提供了丰富的转换器,支持XML、JSON、CSV等格式的转换。
三、工作原理Apache Camel的工作原理可以简单概括为以下几个步骤:1. 定义路由首先,需要定义一个路由来描述消息的流动路径。
路由可以通过Java DSL或XML DSL进行定义,具体的语法和配置方式取决于用户的喜好和应用场景。
Apache Camel是一个用于集成各种消息传递协议和服务的框架,包括Web服务。
在Camel中使用Web服务时,可以使用多种方式处理参数。
以下是一些处理Web服务参数的方法:
1.使用URI参数:当调用Web服务时,可以在URI中传递参数。
这些参数可以在路由中
通过各种方式进行处理,例如使用XPath或Groovy脚本进行提取和转换。
2.使用消息头参数:在Web服务请求中,通常会有一些消息头参数,例如SOAP头或HTTP
头。
这些参数可以在Camel路由中使用header EIP元素进行处理。
3.使用消息体参数:Web服务请求通常包含一个消息体,其中包含需要传递的数据。
在
Camel中,可以使用body EIP元素来访问消息体的内容,并将其传递给其他组件进行处理。
4.使用交换器参数:Camel中的Exchange对象是一个传递Web服务请求和响应的核心
对象。
可以使用exchange属性来访问Exchange对象中的各种参数,例如输入/输出流、异常等。
总之,在Apache Camel中处理Web服务参数的方式非常灵活,可以根据具体的需求选择适合的方法来处理和传递参数。
apache arrow原理Apache Arrow原理分析Apache Arrow是一个用于内存数据交换的开源框架,旨在提供一个跨不同系统和编程语言之间高效传输数据的中间存储格式。
它的设计目标是提供一种高性能、可扩展和可维护的方式来处理大型数据集。
为什么需要Apache Arrow?在大数据场景中,常常涉及到不同系统和编程语言之间的数据传输和处理。
传统上,数据的序列化和反序列化存在性能和内存效率的问题。
此外,一些编程语言的内存布局不同,导致数据在不同的系统中不可共享,进一步增加了转换数据的开销。
Apache Arrow通过定义跨系统和编程语言的统一内存布局来解决这些问题。
它引入了一种称为”缓冲区(Buffer)“的概念,将数据表示为连续的内存块,提供对数据的快速访问。
Apache Arrow的核心概念Apache Arrow的核心概念包括:1. 缓冲区(Buffer)缓冲区是Apache Arrow中的基本数据单元,它是一段连续的内存。
每个缓冲区都有一个偏移量和长度,用于定位和访问其中的数据。
2. 字段(Field)字段是Arrow中的数据的列。
一个字段包含了数据的名称、数据类型以及数据在缓冲区中的存储位置等信息。
字段的元数据可以帮助识别和解释数据。
3. 箭头(Arrow)箭头是一个由字段组成的表,类似于关系型数据库中的表。
每个字段都可以有不同的数据类型和长度,但它们共享相同的行数。
箭头通过缓冲区来存储数据。
4. 数组(Array)数组是由一系列的缓冲区组成的,表示一个字段或多个字段的数据。
数组中的每个缓冲区对应了数据的不同方面,比如存储实际的数据、存储数据的有效性和存储数据的偏移量等。
Apache Arrow的工作流程Apache Arrow的工作流程如下:1.创建一个列数据结构,定义字段和数据类型。
2.将数据加载到缓冲区中,并创建对应的字段和数组。
3.应用计算操作或查询,对数据进行操作,这些操作能够直接访问和处理缓冲区中的数据,无需进行复制或转换。
SpringBootApacheCamel框架面试题Spring Boot Apache Camel框架面试题Apache Camel是一个基于Java的开源集成框架,它提供了大量的企业级集成模式,使得开发者可以轻松地将不同的应用程序、协议和系统进行无缝集成。
在面试中,关于Spring Boot Apache Camel框架的问题经常被提及。
以下是一些常见的面试题以及它们的答案。
1. 请介绍一下Apache Camel框架。
Apache Camel是一个轻量级、可扩展且易于使用的开源集成框架。
它基于企业级集成模式语言,并采用了多种常见的通信协议和数据格式。
Camel提供了一种简单而强大的方式来定义和路由消息,它可以与Spring Boot等流行的Java框架无缝集成。
2. Camel路由是什么?它由哪些组成?在Camel中,路由是处理和转发消息的核心机制。
它由以下几个主要组件组成:- 路由器(Router):根据特定的条件将消息从一个端点路由到另一个端点。
- 处理器(Processor):处理和转换消息的组件。
它可用于对消息进行过滤、转换、聚合等操作。
- 端点(Endpoint):消息的起点和终点,可以是队列、主题、HTTP端点等。
- 组件(Component):用于与外部系统进行通信的组件,如JMS、HTTP、FTP等。
3. Camel如何与Spring Boot集成?要将Camel与Spring Boot集成,需要进行以下步骤:- 引入Camel和Spring Boot的相关依赖。
- 创建一个CamelContext来定义Camel路由。
- 在Spring Boot应用程序的配置类中使用@ImportResource注解导入Camel的配置文件。
- 在配置文件中配置Camel路由。
4. Camel如何实现消息的转换和传输?Camel提供了丰富的转换器和组件来实现消息的转换和传输。
可以使用Camel内置的数据格式转换器,如JSON、XML等,也可以自定义转换器。
java+camel的用法Apache Camel 是一个基于Java 的开源集成框架,用于简化不同系统之间的消息传递和数据交互。
它提供了一种灵活且可扩展的方式来定义和实现路由、转换、路由和中介服务等集成模式。
下面是一个简单的示例,展示了如何在Java 中使用Apache Camel。
1. 引入Camel 依赖:在Maven 项目中,你需要在`pom.xml` 文件中添加Apache Camel 的依赖:```xml<dependencies><dependency><groupId>org.apache.camel</groupId><artifactId>camel-core</artifactId><version>3.14.0</version> <!--使用最新版本--></dependency></dependencies>```2. 创建Camel 路由:在Java 代码中创建Camel 路由。
以下是一个简单的示例,展示了如何创建一个从文件读取数据并将其发送到另一个文件的路由:```javaimport org.apache.camel.builder.RouteBuilder;import org.apache.camel.main.Main;public class MyCamelApp extends Main {public static void main(String[] args) throws Exception {MyCamelApp myCamelApp = new MyCamelApp();myCamelApp.addRouteBuilder(new MyRouteBuilder());myCamelApp.run();}private static class MyRouteBuilder extends RouteBuilder {@Overridepublic void configure() throws Exception {from("file:/path/to/input?noop=true").to("file:/path/to/output");}}}```在这个示例中,我们创建了一个`MyRouteBuilder` 类,继承自`RouteBuilder`,并在`configure` 方法中定义了一个简单的路由。
第一章Camel介绍Apache的Camel™是一种通用的开源集成框架基于已知的企业集成模式。
Camel能够在大量的领域语言中让你定义路由以及中间规则。
定义路由规则的方式主要有两种:Java-based domain-specific language ( DSL ) 和Spring XML。
以下项目利用Apache的Camel作为路由和中介机:Apache ServiceMix -一个流行的分布式开源ESB和JBI容器;Apache ActiveMQ -一个成熟的、广泛使用的开源消息代理;Apache CXF -智能Web服务套件(JAX-WS和JAX-RS);Apache Karaf -一个小的基于OSGi运行时,应用程序可以部署;Apache MINA高性能NIO驱动的网络框架。
一、什么是Camelcamel首先是一个规则引擎。
其次才是一个开源项目。
框架的核心是一个路由引擎,更精确的说是路由引擎制造商。
它允许你定义自己的路由规则,决定从哪个消息来源接受消息,并决定如何处理和发送这些消息。
Apache Camel是Apache基金会下的一个开源项目,提供企业集成模式的实现。
Camel提供的基于规则的路由(Routing)引擎,可以使用Camel定义的DSL语言,方便的定义出各种Routing。
如下例:from(“file://xxxx").to("activemq://xxxx") 将某文件,读入并写入到ActiveMQ的JMS中。
DSL可以用于Java, Scala, Groovy,也可以使用在XML。
如下列:■Java DSLfrom("file:data/inbox").to("jms:queue:order");■Spring DSL<route><from uri="file:data/inbox"/><to uri="jms:queue:order"/></route>■Scala DSLfrom "file:data/inbox" -> "jms:queue:order"丰富的组件库提供了一个超过80个components。
Camel学习Camel学习 (4)⼀.消息类型(Message,Exchange) (4)1) Message (4)2) Exchange (5)⼆.Camel的主要流程: (5)1:创建CamelContext (5)2. 添加Component (5)3.创建Endpoint (6)4.定义路由 (6)5.把路由加⼊context中 (6)6.启动context: (6)三.Camel的路由配置有三种⽅式 (7)1.纯java⽅式创建RouteBuilder (7)2. 纯spring⽅式 (7)3Java+Spring (7)四.路由常⽤模式 (8)1. Using a content-based router(基于内容的路由) (8)/doc/355c5c88f12d2af90342e62c.html ing message filters(消息过滤) (9)3. Using multicasting(多点⼴播) (9)4. Using recipient lists(收件⼈列表模式) (10)6. Using the wireTap method(消息监听,复制) (11)五.数据类型转换 (11)⼀.数据类型转换有两种形式的转换: (11)⼆.Camel提供的消息转换 (12)Using the Message Translator EIP (12)Camel提供了三种⽅式: (12)Using the Content Enricher EIP (13)Transforming XML(XML的转换) (14)1.XSLT格式化 (14)2.XML与JA V A对象的序列化和反序列化 (14)六.⾃定义数据格式化 (14)七.使⽤Camel类型转换器 (14)⼋.如何在Camel中使⽤普通bean (15)⼀.服务代理模式(The Service Activator pattern) (15)⼆. Bean的注册⽅式 (15)三. 选择Bean的⽅法 (16)九.bean的参数绑定 (17)1.1.Binding using built-in types(类型绑定) (17)2. Binding using Camel annotations (注解绑定) (18)⼗.Camel-Core 分析 (19)⼗⼀.Error handling.Camel的错误处理机制 (20)1.irrecoverable error的处理⽅式 (21)2.recoverable error的处理⽅式是: (21)3. Error handlers in Camel(错误处理) (21)4使⽤与返还错误处理程序 (22)/doc/355c5c88f12d2af90342e62c.html ing exception policies(使⽤异常策略) (23)⼗⼆. 测试功能 (23)⼗三. 企业集成模式 (27)■The Aggregator EIP 消息合并 (27)■The Splitter EIP 消息分拆 (29)■The Routing Slip EIP 根据消息标签进⾏路由(也是⼀种路由) (29)■The Dynamic Router EIP 动态路由 (29)■The Load Balancer EIP 负载均衡 (29)Camel学习⼀.消息类型(Message,Exchange)org.apache.camel.Message----是消息的基本的实体。
Camel中的转换:如何进⾏Camel 中的转换:如何进⾏想要你的数据,你的⽅式?了解可以在 Apache Camel 中转换数据的所有不同⽅式。
你如何在 Apache Camel 中转换数据?如果您刚刚,似乎有⼀个令⼈眼花缭乱的选项选择。
处理器?其中的EIP⼀样的东西?消息翻译器?在 Camel 中转换数据通常通过以下⽅式之⼀完成:使⽤ Java 代码和类型转换器进⾏映射使⽤专门的 Camel 组件,如 XSLT、Bindy 或 Atlasmap使⽤数据格式Marshalling/unmarshalling(编组/解组),如 CSV 和 JSON使⽤模板引擎,如、 Mustache 或 FreemarkerCamel 中的转换⽅法:编组、类型转换和模板!那么你怎么知道选择哪⼀个呢?毕竟,他们似乎都在做同样的事情,不是吗?让我们来看看它们中的每⼀个。
我不会在这⾥推荐⼀种⽅法⽽不是另⼀种⽅法。
本⽂旨在为您提供选项的⼴泛概述,以便您可以深⼊研究 Camel ⽂档和⽰例并做出选择。
那么让我们来看看吧!使⽤ Java 代码进⾏转换也被称为……Java架构师的梦想在这种⽅法中,您的输⼊和输出数据都需要是 Java 对象,并且您使⽤ Java 语句在它们之间进⾏映射。
当您需要从源类型转换为⽬标类型时,您可以编写⼀个⽅法来创建⼀个新的⽬标对象,并使⽤源对象中的相关字段填充它。
然后,您告诉 Camel 调⽤该⽅法(例如 using bean,或者可能是Processor)。
例如,您可以将Lead对象转换为Customer. 所以你写了⼀个转换⽅法public static Customer convertToCustomer(Lead lead):public static Customer toCustomer(Lead lead) {Customer customer = new Customer();customer.setName(lead.getName());customer.setCompany(lead.getCompany());customer.setCity(lead.getCity());return customer;}如果您的源数据作为基于⽂本的格式(如 XML )进⼊ Camel,那么⾸先您需要从基于⽂本的格式为 Java 对象,如POJO。
Springboot项⽬集成CamelFTP的⽅法⽰例1、Spring 中集成camel-ftp近期项⽬中涉及到定期获取读取并解析ftp服务器上的⽂件,⾃⼰实现ftp-client的有些复杂,因此考虑集成camel-ftp的⽅式来解决ftp⽂件的下载问题。
⾃⼰则专注于⽂件的解析⼯作.1.1、POM引⽤<dependency><groupId>org.apache.camel</groupId><artifactId>camel-spring-boot-starter</artifactId><version>2.22.1</version></dependency><dependency><groupId>org.apache.camel</groupId><artifactId>camel-ftp</artifactId><version>2.22.1</version></dependency>注意:在选择版本的时候,如果SpringBoot版本是1.5.10.RELEASE的话,那么camel的版本最⾼只能使⽤2.21.2,使⽤2.22版本将会报错。
经测试的配套关系如下:SrpingBoot Camel1.5<=2.21.22.0>=2.22.x其他情况都会出现错误.1.2、SpringBoot application.yml配置ftp:addr: 172.18.18.19:21 # ftp地址、端⼝name: ftpuserpassword: ftp2018options: password=${ftp.password}&readLock=rename&delay=10s&binary=true&filter=#zipFileFilter&noop=true&recursive=trueurl: ftp://${}@${ftp.addr}/?${ftp.options}# 本地下载⽬录local-dir: /var/data# 后台运⾏进程camel:springboot:main-run-controller: truemanagement:endpoint:camelroutes:enabled: trueread-only: true配置说明:delay:每次读取时间间隔filter: 指定⽂件过滤器noop:读取后对源⽂件不做任何处理recursive:递归扫描⼦⽬录,需要在过滤器中允许扫描⼦⽬录readLock:对正在写⼊的⽂件的处理机制更多参数配置见官⽅⼿册1.3、配置路由要配置从远端服务器下载⽂件到本地,格式如下,from内部为我们在上⾯配置的url,to为本地⽂件路径。
JBI User's Guide Apache ServiceMixVersion 4.4.01.Introduction to JBI1.1.What is JBI?TODO: Describe what the JBI specification is all about1.2.Message Exchange PatternsTODO: Describe the four standard JBI MEPs1.3.JBI APITODO: Describe the standard JBI API (MessageExchange, NormalizedMessage, ...)2.JBI Components2.1.servicemix-beanOverviewThe ServiceMix Bean component provides integration with beans (POJOs) with the JBI bus to make it easy to use POJOs to process JBI message exchanges. Like in an Message Driven Bean in J2EE a POJO will receive a message from the NMR and process it in any way it likes. Unlike in a JMS component where the coding is already done the Bean component gives the developer the freedom to create any type of message handling but it must be hand coded all the way.Namespace and xbean.xmlThe namespace URI for the servicemix-bean JBI component is / bean/1.0. This is an example of an xbean.xml file with a namespace definition with prefix bean.<beans xmlns:bean="/bean/1.0"><bean:endpoint service="test:service"endpoint="endpoint"bean="#listenerBean"/><bean id="listenerBean"class="org.apache.servicemix.bean.beans.ListenerBean"/> </beans></beans>Endpoint typesThe servicemix-bean component only defines one endpoint, called bean:endpoint. It can be used to receive and send message exchanges from/to the NMR.Endpoint bean:endpointThere are two ways to configure the bean endpoint. The first is using the fully qualified name of the class and the second is by passing to the endpoint a reference to an existing bean.Using a Java classWhen definining a bean:endpoint specifying a Java class name, a new instance of this class will be created for handling a single message exchange.<beans xmlns:bean="/bean/1.0"xmlns:my="urn:org:servicmix:docs:examples"><bean:endpoint service="my:service"endpoint="endpoint"class="org.apache.servicemix.docs.bean.MyHandlerBean"/> </beans>Using a spring beanAlternative, a reference to an existing bean can be passed to the bean endpoint.<beans xmlns:bean="/bean/1.0"><bean:endpoint service="test:service"endpoint="endpoint"bean="#listenerBean"/><bean id="listenerBean"class="org.apache.servicemix.bean.beans.ListenerBean"/> </beans>Attention: The Bean Endpoint schema allows to set a Bean or a Bean Name. The Bean will create a single instance of the POJO per endpoint whereas the Bean Name will create an instance per request (message exchange).Endpoint propertiesMessageExchangeListenerThe first kind of POJOs you can deploy implement the MessageExchagneListener interface. In such a case,servicemix-bean acts as a replacement of the lightweight container component. This level offers the most control on the exchange received and sent. This is usually used with the injected DeliveryChannel to send back the exchanges, or if the POJOs needs to act as a consumer (i.e. creating and sending exchanges to other services).These POJOs are low-level POJOs: you need to understand the JBI Api and Message Exchange Patterns to correctly handle incoming exchanges.Note that at this point (v 3.1), there is no base class that you can inherit to speed you in this process of implementing a POJO to handle JBI exchanges, but hopefully it will come in the future. ExamplesThis example on the right shows the most simple bean. When it receives an exchange, it will print it to the console and set the status to DONE before sending the exchange back. This bean can not handle InOut exchanges, as it does not set any response (an exception would be thrown in such a case).import javax.annotation.Resource;import javax.jbi.messaging.DeliveryChannel;import javax.jbi.messaging.ExchangeStatus;import javax.jbi.messaging.MessageExchange;import javax.jbi.messaging.MessagingException;public class ListenerBean implements MessageExchangeListener{@Resourceprivate DeliveryChannel channel;public void onMessageExchange(MessageExchange exchange)throws MessagingException{ System.out.println("Received exchange: "+exchange);exchange.setStatus(ExchangeStatus.DONE);channel.send(exchange);}}This example will handle an InOut exchange and will send back the input as the response.Note that this example would fail if receiving an InOnly exchange, as setting a response on an InOnly exchange is not a legal operation.import org.apache.servicemix.jbi.listener.MessageExchangeListener;import org.apache.servicemix.jbi.util.MessageUtil;import javax.annotation.Resource;import javax.jbi.messaging.DeliveryChannel;import javax.jbi.messaging.ExchangeStatus;import javax.jbi.messaging.MessageExchange;import javax.jbi.messaging.MessagingException;public class ListenerBean implements MessageExchangeListener{@Resourceprivate DeliveryChannel channel;public void onMessageExchange(MessageExchange exchange)throws MessagingException{ if(exchange.getStatus()==ExchangeStatus.ACTIVE){MessageUtil.transferInToOut(exchange,exchange);channel.send(exchange);}}}This is similar example as the one from above (also works only for InOut exchange) but it shows how you can extract message from an exchange in order to process it and send back.import org.apache.servicemix.jbi.util.MessageUtil;import org.apache.servicemix.jbi.jaxp.SourceTransformer;import javax.annotation.Resource;import javax.jbi.messaging.DeliveryChannel;import javax.jbi.messaging.ExchangeStatus;import javax.jbi.messaging.MessageExchange;import javax.jbi.messaging.MessagingException;import javax.jbi.messaging.NormalizedMessage;import javax.xml.transform.Source;public class ListenerBean implements MessageExchangeListener{@Resourceprivate DeliveryChannel channel;public void onMessageExchange(MessageExchange exchange)throws MessagingException{ if(exchange.getStatus()==ExchangeStatus.ACTIVE){NormalizedMessage message=exchange.getMessage("in");Source content=message.getContent();//process content according to your logic//e.g. to access the message body as a String useString body=(new SourceTransformer()).toString(content);message.setContent(content);exchange.setMessage(message,"out");channel.send(exchange);}}}DisclaimerIn versions 3.1 to 3.1.2 the ServiceMix Bean component will not handle asynchronous messages correctly because the final send of the message marked as DONE back to the NMR will be handled as a consumer message and that fails because there is no corresponding provider message. The only workaround is to send the messages synchronously.Note: This was resolved in 3.1.3, 3.2.x and later via SM-1110.MessageExchange dispatchingIf the POJO deployed implements the org.apache.servicemix.MessageExchangeListener, every message received for this POJO will be dispatched to the onMessageExchange method.In other cases, exchanges in a provider role will be dispatched according to the MethodInvocationStrategy configured on the endpoint. The default one try to find the method according to the operation name defined on the exchange. If there is only a single method acting as an operation, it will always be used.AnnotationsThe servicemix-bean component can accept different kind of POJOs. These POJOs may be annotated to customize their behavior. All the following annotations belong to theorg.apache.servicemix.bean package.Annotation Target DescriptionIn addition, standard annotations can be used:The following interfaces are part of this API:More Examples•AnnotatedBean•AutoDeployedBean•ConsumerBean•ListenerBean•PlainBean2.2.servicemix-camelOverviewThe servicemix-camel component provides support for using Apache Camel to provide a full set of Enterprise Integration Patterns and flexible routing and transformation in both Java code or Spring XML to route services on the Normalized Message Router.Namespace and camel-context.xmlWhen creating a servicemix-camel service unit, we reuse the default Camel namespace/schema/spring.This is an example camel-context.xml which uses the Spring DSL to define the Camel routes <?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-2.0.xsd/schema/spring/schema/spring/camel-spring.xsd"><camelContext xmlns="/schema/spring"><route><!-- route defined in the Spring DSL --></route></camelContext></beans>It is also possible to use the Java DSL inside a servicemix-camel service unit by referring to the package that contains the RouteBuilder classes. An example: this camel-context.xml file will activate all routes defined by RouteBuilder s in the org.apache.servicemix.example.camel package.<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-2.0.xsd/schema/spring/schema/spring/camel-spring.xsd"><camelContext xmlns="/schema/spring"><packages>org.apache.servicemix.examples.camel</packages></camelContext></beans>URICamel routes use URIs to interact with the ESB. You can use these URIs to expose new endpoints on the ESB as well as to send message exchanges to existing endpoints.The snippet below automatically exposes a new endpoint to the bus, where the service QName is MyService and the endpoint name is MyEndpoint.from("jbi:endpoint:/MyService/MyEndpoint")When a JBI endpoint appears at the end of a route, as in the example below, that will send to("jbi:endpoint:/MyService/MyEndpoint")The messages sent by this producer endpoint are sent to the already deployed JBI endpoint.URI formatjbi:service:serviceNamespace[sep]serviceName[?options]jbi:endpoint:serviceNamespace[sep]serviceName[sep]endpointName[?options]jbi:name:endpointName[?options]The separator that should be used in the endpoint URL is:•/(forward slash), if serviceNamespace starts with http://•:(colon), if serviceNamespace starts with urn:.You can append query options to the URI in the following format,?option=value&ption=value&.. ExamplesUsing jbi:servicejbi:service:/MyServicejbi:service:urn:foo:bar:MyServiceUsing jbi:endpointjbi:endpoint:urn:foo:bar:MyService:MyEndpointjbi:endpoint:/MyService/MyEndpointUsing jbi:nameWhen using jbi:name, the component uses /camel/schema/jbi}endpoint as the default Service QName.jbi:name:MyEndpointURI optionsName Default value Descriptionmep MEP of theCamelExchangeAllows users to override the MEP set on the Exchange object. Validvalues for this option are in-only,in-out,robust-in-out and in-optional-out.operation Value of thejbi.operationheader propertySpecifies the JBI operation for the MessageExchange. If no value issupplied, the JBI binding will use the value of the jbi.operation headerproperty.serialization basic Default value (basic) will check if headers are serializable by looking at the type, setting this option to strict will detect objects that can not be serialized although they implement the Serializable interface. Set to nocheck to disable this check altogether, note that this should only be used for in-memory transports like SEDAFlow, otherwise you can expect to get NotSerializableException thrown at runtime.convertException false false: send any exceptions thrown from the Camel route back unmodifiedtrue: convert all exceptions to a JBI FaultException (can be used to avoidnon-serializable exceptions or to implement generic error handlingExamplesjbi:service:/MyService?mep=in-out (override the MEP, use InOut JBI MessageExc jbi:endpoint:urn:foo:bar:MyService:MyEndpoint?mep=in (override the MEP, use InOnly JBI MessageEx jbi:endpoint:urn:foo:bar:MyService:MyEndpoint?operation={}AddNumbers(overide the operation for the JBI Exchange to {}AddNumbers)Example routesSimple Spring routeThis simple Spring route registers a new endpoint on the ESB (service Router, endpoint nameorders). The message exchange contents will be logged and then forwarded to another JBI serviceendpoint (service OrderService)<beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-2.0.xsd/schema/spring/schema/spring/camel-spring.xsd"><camelContext xmlns="/schema/spring"><route><from uri="jbi:endpoint:urn:org:example:Router:orders"/><to uri="log:OrderLogging"/><to uri="jbi:service:/OrderService"/></route></camelContext></beans>The same route using the Java DSLWhen we implement the same route in the Java DSL, we first code our RouteBuilderimplementationpackage org.apache.servicemix.example;import org.apache.camel.builder.RouteBuilder;public class JbiRouteBuilder extends RouteBuilder{@Overridepublic void configure()throws Exception{from("jbi:endpoint:urn:org:example:Router:orders").to("log:OrderLogging").to("jbi:service:/OrderService");}}In our camel-context.xml file, we just refer to the org.apache.servicemix.example packagethat contains our JbiRouteBuilder.<beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-2.0.xsd/schema/spring/schema/spring/camel-spring.xsd"><camelContext xmlns="/schema/spring"><route><packageScan><package>org.apache.servicemix.example</package></packageScan></route></camelContext></beans>Special considerationsStream handlingIf you are using a stream type as the message body, you should be aware that a stream is only capable of being read once. So if you enable DEBUG logging, the body is usually logged and thus read. To deal with this, Camel has a streamCaching option that can cache the stream, enabling you to read it multiple times.from("jbi:endpoint:/MyService/MyEndpoint").streamCaching().to("xslt:transform.xsl","bean:doSomething");Camel will cache large input streams (by default, over 64K) in a temp file usingCachedOutputStream. When you close the input stream, the temp file will be deleted.2.3.servicemix-cxf-bcOverviewA JBI compliant HTTP/SOAP or JMS/SOAP binding component named servicemix-cxf-bc which useapache cxf internally.The main features are:•JBI compliant Binding Component•Usable in a lightweight mode in servicemix.xml configuration files•SOAP 1.1 and 1.2 support•MIME attachments•Support for all MEPs as consumers or providers•SSL support•WS-Security support•WS-Policy support•WS-RM support•WS-Addressing supportNamespace and xbean.xmlThe namespace URI for the servicemix-bean JBI component is / cxfbc/1.0. This is an example of an xbean.xml file with a namespace definition with prefix bean.<beans xmlns:cxfbc="/cxfbc/1.0"><!-- add cxfbc:consumer or cxfbc:provider definitions here --></beans>Endpoint typesThe servicemix-cxf-bc component defines two endpoints:▪cxfbc:consumer:: a server-side cxf endpoint that will consume plain HTTP+SOAP requests and send them into the NMR to a given JBI endpoint▪cxfbc:provider:: a client-side jbi endpoint which can receive requests from the NMR and send them to a given url where the service is providedcxfbc:consumerEndpoint propertiesProperty Name Type DescriptionbusCfg ng.String the location of the CXF configuration file used to configure the CXF bus. This allows you to configure features like WS-RM and JMS runtime behavior.delegateToJaas boolean Specifies if the endpoint delegate to JAASAuthenticationService to do the authentication.endpoint ng.String The name of the endpoint.features(ng.Object)\*Specifies the cxf features set for thisendpointinFaultInterceptors(ng.Object)\* a list of beans configuring interceptors thatprocess incoming faultsinInterceptors(ng.Object)\* a list of beans configuring interceptors thatprocess incoming responsesinterfaceName space.QName The qualified name of the interface exposedby the endpoint.locationURI ng.String the HTTP address to which requests are sent. This value will overide any value specified in the WSDL.mtomEnabled boolean Specifies if MTOM / attachment support isenabled. Default is <code>false</code>.outFaultInterceptors(ng.Object)\*a list of beans configuring interceptors that process fault messages being returned to the consumeroutInterceptors(ng.Object)\* a list of beans configuring interceptors thatprocess requestsproperties java.util.Map Sets arbitrary properties that are added tothe CXF context at the Endpoint levelprovidedBus org.apache.cxf.Bus a preconfigured CXF Bus object to use;overrides busCfgschemaValidationEnabled boolean Specifies if the endpoint use schemavalidation for the incoming/outgoing message.service space.QName The qualified name of the service theendpoint exposes.synchronous boolean Specifies if the endpoint expects sendmessageExchange by sendSync .targetEndpoint ng.String the name of the endpoint to which requestsare senttargetInterface space.QName the QName of the interface to whichrequests are senttargetOperation space.QName the QName of the operation to whichrequests are senttargetService space.QName the QName of the service to which requestsare senttargetUri ng.String Set the target service/endpoint/interfaceusing a URI.timeout long the number of second the endpoint will waitfor a response. The default is unlimited.useJBIWrapper boolean Specifies if the JBI wrapper is sent in the body of the message. Default is<code>true</code>.useSOAPEnvelope boolean Specifies if the endpoint expects soapmessages when useJBIWrapper is false,wsdl org.springframework.core.io.Resource the location of the WSDL document definingthe endpoint's interfacex509boolean Specifies if the endpoint use X.509Certificate to do the authentication. cxfbc:providerEndpoint propertiesProperty Name Type DescriptionbusCfg ng.String the location of the CXF configuration file used to configure the CXF bus. This allows you to configure features like WS-RM and JMS runtime behavior.endpoint ng.String The name of the endpoint.features(ng.Object)\*Specifies the cxf features set for thisendpointinFaultInterceptors(ng.Object)\* a list of beans configuring interceptors thatprocess incoming faultsinInterceptors(ng.Object)\* a list of beans configuring interceptors thatprocess incoming requestsinterfaceName space.QName The qualified name of the interface exposedby the endpoint.locationURI .URI the HTTP address of the exposed service. This value will overide any value specified in the WSDL.mtomEnabled boolean Specifies if MTOM / attachment support isenabled. Default is <code>false</code>.outFaultInterceptors(ng.Object)\*a list of beans configuring interceptors that process fault messages being returned to the consumeroutInterceptors(ng.Object)\* a list of beans configuring interceptors thatprocess responsesproperties java.util.Map Sets arbitrary properties that are added tothe CXF context at the Endpoint levelprovidedBus org.apache.cxf.Bus a preconfigured CXF Bus object to use;overrides busCfgschemaValidationEnabled boolean Specifies if the endpoint use schemavalidation for the incoming/outgoing message.service space.QName The qualified name of the service theendpoint exposes.synchronous boolean Specifies if the endpoints send message synchronously to external server using underlyinguseJBIWrapper boolean Specifies if the JBI wrapper is sent in the body of the message. Default is<code>true</code>.useSOAPEnvelope boolean Specifies if the endpoint expects soapmessages when useJBIWrapper is false,wsdl org.springframework.core.io.Resource the location of the WSDL document definingthe endpoint's interfaceExamplesConfiguring the CXF JMS TransportThe ServiceMix CXF binding component also allows using the CXF JMS Transport to send and receive messages. You can use the<cxf:features/>element to add and configure theorg.apache.cxf.transport.jms.JMSConfigFeature on the endpoint, as in the example below.service="greeter:HelloWorldService"endpoint="HelloWorldPortProxy"interfaceName="greeter:Greeter"busCfg="jms_conduit_config.xml"><!-- add interceptors here --><cxfbc:features><bean class="org.apache.cxf.transport.jms.JMSConfigFeature"><property name="jmsConfig"><bean class="org.apache.cxf.transport.jms.JMSConfiguration"><property name="concurrentConsumers"><value>5</value></property><property name="connectionFactory"><ref bean="myConnectionFactory"/></property><property name="targetDestination"><value>test.jmstransport.text.provider</value></property><property name="useJms11"><value>false</value></property></bean></property></bean></cxfbc:features></cxfbc:provider><amq:connectionFactory id="myConnectionFactory"brokerURL="vm://localhost"/>The jms_conduit_config.xml file specified in the busCfg parameter, is optional and can be usedto specify additional JMS transport parameters:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:jms="/transports/jms"xsi:schemaLocation="/transports/jms /schemas/configuration/jms.xsd/schema/beans /schema/beans/spring <jms:conduit name="{/hello_world_soap_http}HelloWorldPort.jms-conduit"abstract= <jms:clientConfig clientReceiveTimeout="200000"/></jms:conduit></beans>Configuring the CXF HTTP TransportIn order to configure the underlying HTTP transport used by a CXF BC endpoint, you can specify anadditional busCfg file as in the example below.service="greeter:HelloWorldService"endpoint="HelloWorldPortProxy"interfaceName="greeter:Greeter"busCfg="http_conduit_config.xml"><!-- add interceptors and additional CXF features here --></cxfbc:provider>The http_conduit_config.xml file can then specify the additional CXF configuration. Have a lookat this page for an overview of all the options supported by CXF.<beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:http-conf="/transports/http/configuration"xsi:schemaLocation="/transports/http/configuration/schemas/configuration/http-conf.xsd/schema/beans/schema/beans/spring-beans.xsd"> <http-conf:conduit name="{/hello_world_soap_http}HelloWorldPort.http-conduit"> <http-conf:client Connection="Keep-Alive"MaxRetransmits="1"AllowChunking="false"/></http-conf:conduit></beans>2.4.servicemix-cxf-seOverviewServiceMix CXF SE component is a JBI Service Engine exposing (annotated) POJO as services on theJBI Bus.It uses Apache CXF internally to perform service invocations and xml marshaling.Features:•jsr181 annotations•jaxb2/aegis/xmlbeans databinding•wsdl auto generation•java proxy support•MTOM / attachments supportNamespace and xbean.xmlThe namespace URI for the servicemix-bean JBI component is /cxfse/1.0. This is an example of an xbean.xml file with a namespace definition with prefix bean.<beans xmlns:cxfse="/cxfse/1.0"><!-- add cxfse:endpoint definitions here --></beans>Endpoint typesThe servicemix-cxf-bc component defines one endpoint type:▪cxfse:endpoint:: no description yetcxfse:endpointEndpoint propertiesProperty Name Type Descriptionendpoint ng.String The name of the endpoint.inFaultInterceptors(ng.Object)\* a list of beans configuring interceptors that processincoming faultsinInterceptors(ng.Object)\* a list of beans configuring interceptors that processincoming requestsinterfaceName space.QName The qualified name of the interface exposed by theendpoint.mtomEnabled boolean Specifies if the service can consume MTOM formattedbinary data. The default is <code>false</code>.outFaultInterceptors(ng.Object)\* a list of beans configuring interceptors that process faultmessages being returned to the consumeroutInterceptors(ng.Object)\* a list of beans configuring interceptors that processresponse messagespojo ng.Object a bean configuring the JAX-WS annotated implementationfor the endpointpojoEndpoint space.QName Specifies the servicemodel endpoint name generated fromthe pojo. The default is <code>null</code>.pojoInterfaceName space.QName Specifies the servicemodel interface name generated fromthe pojo. The default is <code>null</code>.pojoService space.QName Specifies the servicemodel service name generated fromthe pojo. The default is <code>null</code>.properties java.util.Map Specifies a map of propertiesservice space.QName The qualified name of the service the endpoint exposes.useAegis boolean Specifies if the endpoint use aegis databinding to marshall/unmarshall message. The default is<code>false</code>.useJBIWrapper boolean Specifies if the endpoint expects to receive the JBI wrapper in the message received from the NMR. The default is<code>true</code>. Ignore the value of useSOAPEnvelope if useJBIWrapper is trueuseSOAPEnvelope boolean Specifies if the endpoint expects soap messages when useJBIWrapper is false, if useJBIWrapper is true then ignore useSOAPEnvelope. The default is <code>true</code>.useXmlBeans boolean Specifies if the endpoint use xmlbeans databinding to marshell/unmarshell message. The default is<code>false</code>.cxfbc:proxyEndpoint propertiesProperty Name Type DescriptioncomponentRegistry ng.Object Allows injecting a custom component registry for looking up the proxying endpoint.container org.apache.servicemix.jbi.api.Container Allows injecting a JBI Container instance(e.g. for testing purposes).context ponentContext Allows injecting the ComponentContext endpoint ng.String The name of the endpoint.factory org.apache.servicemix.jbi.api.ClientFactory Allows injecting a ClientFactoryinterfaceName space.QName Specifies the servicemodel interfacenamemtomEnabled boolean Specifies if the service can consume MTOM formatted binary data. The default is <code>false</code>.name ng.String Specifies the JNDI name for looking up the ClientFactory. Defaults to<code>java:comp/env/jbi/ ClientFactory</code>.propagateSecuritySubject boolean When set to <code>true</code>, the security subject is propagated along to the proxied endpoint. Defaults to<code>false</code>.service space.QName Specifies the servicemodel service name type ng.Class Specifies the webservice POJO typeuseJBIWrapper boolean Specifies if the endpoint expects to receive the JBI wrapper in the message received from the NMR. The default is <code>true</code>. Ignore the value of useSOAPEnvelope if useJBIWrapper is trueuseSOAPEnvelope boolean Specifies if the endpoint expects soap messages when useJBIWrapper is false, if useJBIWrapper is true then ignore useSOAPEnvelope. The default is<code>true</code>.2.5.servicemix-droolsOverviewThe ServiceMix Drools component provides JBI integration to the Drools Rules Engine.This Service Engine can be used to deploy a rules set that will implement a router or an actual service.A router will mostly act as a transparent proxy between the consumer and the target serviceprovider mad will mostly be implemented by the jbi.route(uri) method below. This method creates a new exchange identical to the one received by the component and will send it to the specified destination. You can also send back a Fault if needed. A router can also be implemented by using directly the JBI Apis (available with the jbi helper) by using the provided client.Namespace and xbean.xmlThe namespace URI for the servicemix-bean JBI component is / drools/1.0. This is an example of an xbean.xml file with a namespace definition with prefix bean.。
Apache Camel框架入门示例分类:Camel2012-02-03 15:42 8527人阅读评论(6) 收藏举报apache框架exceptionexchangefilewebserviceApache Camel是Apache基金会下的一个开源项目,它是一个基于规则路由和处理的引擎,提供企业集成模式的Java对象的实现,通过应用程序接口或称为陈述式的Java领域特定语言(DSL)来配置路由和处理的规则。
其核心的思想就是从一个from源头得到数据,通过processor处理,再发到一个to目的的.这个from和to可以是我们在项目集成中经常碰到的类型:一个FTP文件夹中的文件,一个MQ的queue,一个HTTP request/response,一个webservice等等.Camel可以很容易集成到standalone的应用,在容器中运行的Web应用,以及和Spring一起集成.下面用一个示例,介绍怎么开发一个最简单的Camel应用.1,从/download.html下载Jar包.在本文写作的时候最新版本是2.9. 本文用的是2.7,从2.7开始要求需要JRE1.6的环境.下载的zip包含了Camel各种特性要用到的jar包.在本文入门示例用到的Jar包只需要:camel-core-2.7.5.jar,commons-management-1.0.jar,slf4j-api-1.6.1.jar.2,新建一个Eclipse工程,将上面列出的jar包设定到工程的Classpath.新建一个如下的类:运行后完成的工作是将d:/temp/inbox/下的所有文件移到d:/temp/outbox [java]view plaincopy1.public class FileMoveWithCamel {2.public static void main(String args[]) throws Exception {3. CamelContext context = new DefaultCamelContext();4. context.addRoutes(new RouteBuilder() {5.public void configure() {6.//from("file:d:/temp/inbox?noop=true").to("file:d:/temp/outbox");7. from("file:d:/temp/inbox/?delay=30000").to("file:d:/temp/outbox");8. }9. });10. context.start();11.boolean loop =true;12.while(loop){13. Thread.sleep(25000);14. }15. context.stop();16. }17.}上面的例子体现了一个最简单的路由功能,比如d:/temp/inbox/是某一个系统FTP到Camel 所在的系统的一个接收目录.d:/temp/outbox为Camel要发送的另一个系统的接收目录.from/to可以是如下别的形式,读者是否可以看出Camel是可以用于系统集成中做路由,流程控制一个非常好的框架了呢?from("file:d:/temp/inbox/?delay=30000").to("jms:queue:order");//delay=30000是每隔30秒轮询一次文件夹中是否有文件.3,再给出一个从from到to有中间流程process处理的例子:[java]view plaincopy1.public class FileProcessWithCamel {2.public static void main(String args[]) throws Exception {3. CamelContext context = new DefaultCamelContext();4. context.addRoutes(new RouteBuilder() {5.6.public void configure() {7. FileConvertProcessor processor = new FileConvertProcessor();8. from("file:d:/temp/inbox?noop=true").process(processor).to("file:d:/temp/outbox");9. }10. });11.12. context.start();13.boolean loop =true;14.while(loop){15. Thread.sleep(25000);16. }17. context.stop();18. }19.}这里的处理只是简单的把接收到的文件多行转成一行[java]view plaincopy1.public class FileConvertProcessor implements Processor{2.@Override3.public void process(Exchange exchange) throws Exception {4.try {5. InputStream body = exchange.getIn().getBody(InputStream.class);6. BufferedReader in = new BufferedReader(new InputStreamReader(body));7. StringBuffer strbf = new StringBuffer("");8. String str = null;9. str = in.readLine();10.while (str != null) {11. System.out.println(str);12. strbf.append(str + " ");13. str = in.readLine();14. }15. exchange.getOut().setHeader(Exchange.FILE_NAME, "converted.txt");16.// set the output to the file17. exchange.getOut().setBody(strbf.toString());18. } catch (IOException e) {19. e.printStackTrace();20. }21. }22.}在Eclipse里运行的时候,Camel默认不会把log信息打印到控制台,这样出错的话,异常是看不到的,需要把log4j配置到项目中.[java]view plaincopy1.log4j.appender.stdout = org.apache.log4j.ConsoleAppender2.log4j.appender.stdout.Target = System.outyout = org.apache.log4j.PatternLayoutyout.ConversionPattern = %-5p %d [%t] %c: %m%n5.log4j.rootLogger = debug,s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Apache Camel 框架集成SpringApache Camel提供了和Spring的集成,通过Spring容器(ApplicationContext)来管理Camel 的CamelContext,这样的话,就不需要写代码来控制CamelContext的初始化,启动和停止了.Camel会随着Spring的启动而启动起来.本文将Apache Camel 框架入门示例(/kkdelta/article/details/7231640)中的例子集成到Spring 中,下面简单介绍一下集成的基本步骤.1,新建一个Eclipse 工程,将Spring3的jar 包,和Camel 的jar 包配置到工程的classpath. 2,Route 类要继承RouteBuilde,如下1 public class FileProcessWithCamelSpring extends RouteBuilder {2 @Override3 public void configure() throws Exception {4 FileConvertProcessor processor = new FileConvertProcessor();5 from("file:d:/temp/inbox?delay=30000").process(processor).to ("file:d:/temp/outbox");6}7 }3,Processor 仍然和和入门示例的代码相同. 01 public class FileConvertProcessor implements Processor{02 @Override03 public void process(Exchange exchange) throws Exception { 04 try {05 InputStream body = exchange.getIn().getBody(InputStream.class);06 BufferedReader in = new BufferedReader(new InputStreamReader(body));07 StringBuffer strbf = new StringBuffer("");08 String str = null;09 str = in.readLine();10 while (str != null) {11 System.out.println(str);12 strbf.append(str + " ");13 str = in.readLine();14 }15 exchange.getOut().setHeader(Exchange.FILE_NAME, "conve rted.txt");16 // set the output to the file17 exchange.getOut().setBody(strbf.toString());18 } catch (IOException e) {19 e.printStackTrace();20 }21 }2223 }4,创建一个Spring的配置文件如下:注意要将camel的xmlns加入文件中01 <?xml version="1.0" encoding="UTF-8"?>02 <beans xmlns="/schema/beans"03 xmlns:xsi="/2001/XMLSchema-instance"04 xmlns:camel="/schema/spring"0 5 xsi:schemaLocation="/schema/bean s /schema/beans/spring-beans-3.0.xsd0 6 /schema/spring/schema/spring/camel-spring.xsd"07 default-autowire="byName" default-init-method="init">0 8 <camelContext id="testCamelContext" xmlns="http://camel.apache. org/schema/spring">09 <package>com.test.camel</package>10 </camelContext>11 </beans>5,启动Spring容器,Camel会自动启动,不用像入门示例那样CamelContext context = new DefaultCamelContext(), context.addRoutes(..); context.start();ApplicationContext ac = newClassPathXmlApplicationContext("config/cameltest.xml");while (true) {Thread.sleep(2000);}可见,Camel可以很容易的和Spring集成.Camel还提供了"Spring DSL"来在XML中配置Route规则,不需要用JAVA类(如上面的FileProcessWithCamelSpring )来实现route.查看源码打印?01 <?xml version="1.0" encoding="UTF-8"?>02 <beans xmlns="/schema/beans"03 xmlns:xsi="/2001/XMLSchema-instance"04 xmlns:camel="/schema/spring"0 5 xsi:schemaLocation="/schema/bean s /schema/beans/spring-beans-3.0.xsd0 6 /schema/spring/schema/spring/camel-spring.xsd"07 default-autowire="byName" default-init-method="init">0 8 <bean id="fileConverter" class="com.test.camel.FileConvertProc essor"/>0 9 <camelContext id="testCamelContext" xmlns="http://camel.apache. org/schema/spring">10 <route>11 <from uri="file:d:/temp/inbox?delay=30000"/>12 <process ref="fileConverter"/>13 <to uri="file:d:/temp/outbox"/>14 </route>15 </camelContext>1617 </beans>与第五步一样启动Spring容器,Camel会每隔30秒轮询一下看d:/temp/inbox是否有文件,有的话则进行处理.WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWApache Camel框架之FTP路由您的评价: 收藏该经验在做项目集成类型的项目的时候,经常会有这样的需求,用户或者别的系统将文件传到一个FTP server,然后系统从FTP server取文件进行相应的处理.本文简单的介绍和示例一个用Camel实现这样的需求:监听FTPserver是否有文件,取到文件做相应处理传到另外一个系统.1,搭建一个FTP server,从/projects/filezilla/files/ 下载FileZilla安装,设置一个用户yorker/123456.可以参照这个网址/filezilla-server.htm2,在Camel里实现路由:查看源码打印?01 CamelContext context = new DefaultCamelContext();02 context.addRoutes(new RouteBuilder() {03 public void configure() {0 4 from("ftp://localhost/inbox?username=yorker&password=12345 6").to(05 "file:d:/temp/outbox");06 }07 });08 context.start();09 boolean loop = true;10 while (loop) {11 Thread.sleep(25000);12 }1314 context.stop();这里主要是为了示例Camel对FTP的支持,没有加入processor的处理,downstream system 也仅仅是用放到本地文件夹做示例.不过真正做项目的时候,在to里可以是别的类型,如JMS 的queue,别的系统的FTB inbound文件夹,Web service等等.如何在流程的中间加入processor 处理可以参见/kkdelta/article/details/7231640WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWApache Camel 框架之JMS 路由您的评价: 收藏该经验继上次Camel 如何在做项目集成类型的项目中用于从FTP 取文件和传文件之后,我们在系统集成中经常遇到的另一个应用就是将数据通过JMS 传到消息中间件的queue 里,或者从消息中间件的queue 里取消息.本文简单的介绍和示例一个用Camel 实现这样的需求:监听某一个文件夹是否有文件,取到文件后发送到另外一个系统监听的queue.1,因为要用JMS,这里介绍一个open source 的activeMQ,可以从/download.html 下载,下载后解压,bin 目录有一个activemq.bat 文件,在命令行里运行activemq 启动activeMQ,如果能从从浏览器里访问http://localhost:8161/admin/则activeMQ 成功启动了.2,在Camel 里实现上图所示的路由:JAVA 项目里需要将activeMQ 的jar 包配置到classpath 下,Java 代码如下:01 private static String user = ActiveMQConnection.DEFAULT_USER; 02 private static String password = ActiveMQConnection.DEFAULT_PASSWORD;03 private static String url = ActiveMQConnection.DEFAULT_BROKER_URL; 0405 public static void main(String args[]) throws Exception { 06 CamelContext context = new DefaultCamelContext(); 07 ConnectionFactory connectionFactory =08 new ActiveMQConnectionFactory(user, password, url); 09 context.addComponent("jms",10 JmsComponent.jmsComponentAutoAcknowledge(connectionFactory ));11 System.out.println(url + " " + user + password); 12 context.addRoutes(new RouteBuilder() {13 public void configure() {14 from("file:d:/temp/inbox").to(15 "jms:queue:TOOL.DEFAULT");16 }17 });18 context.start();19 boolean loop = true;20 while (loop) {21 Thread.sleep(25000);22 }2324 context.stop();25 }Camel 会在路由的时候将文件的内容以binary message 发到activeMQ 的名为'TOOL.DEFAULT'的queue .用下面的代码可以从Camel 发送的queue 里取到消息.查看源码打印?01 private static String user = ActiveMQConnection.DEFAULT_USER; 02 private static String password = ActiveMQConnection.DEFAULT_PASSWORD;03 private static String url = ActiveMQConnection.DEFAULT_BROKER_URL; 04 private static boolean transacted;05 private static int ackMode = Session.AUTO_ACKNOWLEDGE;0607 public static void main(String[] args) throws Exception {08 ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);09 Connection connection = connectionFactory.createConnection(); 10 connection.start();11 Session session = connection.createSession(transacted, ackMode); 12 Destination destination = session.createQueue("TOOL.DEFAULT"); 13 MessageConsumer consumer = session.createConsumer(destination); 14 Message message = consumer.receive(1000);1516 System.out.println("Received: " + message);17 BytesMessage bytesMsg = (BytesMessage) message;18 byte[] bytes = new byte[(int) bytesMsg.getBodyLength()]; 19 bytesMsg.readBytes(bytes);20 System.out.println("contents: " + new String(bytes)); 21 }CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCApache Camel 框架之HTTP 路由您的评价: 收藏该经验继介绍完Camel 如何处理FTP,JMS 接口之后,今天介绍一下系统集成的时候经常遇到的另一个接口,HTTP,一个示例需求如下图所示:本文给出一个简单的代码示例如何用Camel 来实现这样一个应用:1,在一个JAVA 类里配置如下路由:这里只示例了HTTP 的部分,其他功能实现可以参见Apache Camel 框架系列的其他博客.01 public class HttpPollWithQuartzCamel {02 public static void main(String args[]) throws Exception { 03 CamelContext context = new DefaultCamelContext();04 context.addRoutes(new RouteBuilder() {05 public void configure() {06 from("quartz://report?cron=10 * * * * ?&stateful=true")07 .to("http://localhost:8080/prjWeb/test.camelreq") 08 .to("file:d:/temp/outbox?fileName=http.csv"); 09 );10 }11 });12 context.start();13 boolean loop = true;14 while (loop) {15 Thread.sleep(25000);16 }17 context.stop();18 }19 }对上面代码的简单解释: from("quartz://report?cron=10 * * * * ?&stateful=true"),配置一个quartz Job,每隔10秒发送一个HTTP request,将收到的内容保存为文件.这里的http url 可以是任何可以访问的http url,如果在http 访问时候需要代理可以这么配置:"?proxyHost=&proxyPort=8080"这个例子需要用到quartz,和httpclient 等jar 包,可以从这里下载:/detail/kkdelta/4051072&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&7针对 Java 开发者的 Apache Camel 入门指南您的评价:收藏该经验Apache Camel是一个非常实用的规则引擎库,能够用来处理来自于不同源的事件和信息。