apache camel_Apache Camel –从头开始开发应用程序(第1部分/第2部分)

本文档是关于如何使用Apache Camel构建一个发票处理系统的教程,该系统接收发票,进行过滤和路由。内容涵盖了Camel的核心概念,如Camel上下文、消息、Exchange、路由和处理器。文章首先介绍了系统的功能和架构,然后逐步指导读者创建项目,包括初始化Camel、实现发票网关、发票分割器、过滤器和基于内容的路由器。此外,还讨论了如何使用SEDA组件进行内存中消息传递。
摘要由CSDN通过智能技术生成

apache camel

开始之前

前段时间,我写了一篇关于Spring Integration的教程,以演示如何在受现实发票处理系统启发的示例应用程序中使用Spring Integration。 我对此非常满意,因此我决定向您展示如何使用Apache Camel(Spring Integration的最大竞争对手)构建完全相同的应用程序。

我们将要构建的应用程序几乎相同,因此本教程中的很多文字也将如此。 新部分将主要集中在Apache Camel及其用法上。

您可以逐步按照本教程操作,并从头开始创建应用程序,也可以继续从github获取代码:在此处下载源: https : //github.com/vrto/apache-camel-invoices

请注意,还有更多方法来编写骆驼“路线” – Java DSL,Spring XML,Scala DSL…在本教程中,我将使用Java DSL ,但对于那些感兴趣的人–您也可以在此处找到通过Spring XML配置的相同项目。 。 无论您喜欢哪种方式,都该开始了!

发票处理申请书-功能说明

想象一下,您正在为某家公司工作,该公司会定期从各种承包商那里收到大量发票。 我们将建立一个能够接收发票,过滤掉相关发票,创建付款(本地或国外)并将其发送到某些银行服务的系统。 即使该系统非常幼稚,当然也不适合企业使用,我们仍将尝试以良好的可伸缩性,灵活性和分离的设计来构建它。

Apache Camel是一个集成框架–这意味着它为要集成的复杂系统提供了有意义的抽象。
本教程有很多重要的概念需要理解。 让我为您总结一下:

  • 骆驼上下文 :将所有部分保持在一起的运行时系统。
  • 消息 :基本实体–消息传递的核心原理。 它由标题正文附件组成
  • Exchange :消息的容器(对通过系统实际发送的内容的抽象)。 它包含In消息,还可以包含Out消息。
  • 路线 :处理器链。 如果您更喜欢“学术”解释,则路由是一个图形,其中“节点”由某个处理器表示,“线”由某个通道表示。
  • 处理器 :使用/修改传入的交换。 一个处理器的输出连接到另一处理器的输入。
  • 端点 :建模通道末端。 使用URI进行配置。 例:
    file:data/inbox?delay=5000
  • 组件 :端点工厂。 用前缀引用(jms:,file:等)。

如果您想了解有关骆驼核心概念的更多详细信息,强烈建议您阅读非常好的《 骆驼在行动》一书。

现在,我们对基本概念有了一些了解,让我们看一下下面的图片,它是系统的摘要,并遍历了重要的部分:

整合发票

在图片上,您可以看到一条路线,该路线示出了我们的消息传递结构和系统的核心组件-它们用红色数字标记。 让我们来看一下(稍后我们将更详细地介绍每个组件):

  1. 发票网关 –这是我们放置新发票以便它们可以进入消息传递层的地方。
  2. 拆分器 -该系统旨在接受发票的集合,但是我们将需要单独处理每个发票。 更具体地说,具有“收集”类型正文的邮件将被拆分为多个邮件,其中每个邮件将具有单独的发票作为正文。
  3. 筛选器 -我们的系统旨在仅自动处理开具少于$ 10,000的那些发票。
  4. 基于内容的路由器 -有些发票使用IBAN帐号,我们有两个不同的帐号-一个用于本地交易,一个用于国外交易。 路由器组件的工作是将带有发票的消息发送到正确的通道-无论是本地发票还是国外发票。
  5. 变形金刚 –在我们将发票接收到系统中的同时,我们的银行API也可以与其他类型一起使用–付款。 转换器组件的工作是根据提供的逻辑获取一些消息并将其转换为另一条消息。 我们希望将原始消息(发票)的有效负载转换为新的有效负载-付款。
  6. 银行服务激活程序 –处理发票并生成一些实际付款后,我们准备与外部银行系统进行对话。 我们已经公开了此类系统的服务,当携带付款的消息进入正确的(银行)渠道时,我们想激活一些逻辑–将付款传递给银行,然后让银行进行进一步处理。

创建项目

到目前为止,您应该对系统的功能以及其结构有一个较高的概述。 在开始编码之前,您将需要一个实际的Maven项目,并设置结构和所需的依赖关系。 如果您熟悉Maven,请在下面查看pom.xml文件,否则,如果您想节省一些时间,欢迎使用我为您创建的项目模板: 下载Maven项目模板

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>apache-camel-invoices</groupId>
    <artifactId>apache-camel-invoices</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <camel-version>2.12.0</camel-version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>${camel-version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>${camel-version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-quartz</artifactId>
            <version>2.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test-spring</artifactId>
            <version>${camel-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>14.0.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
			<!--

			- uncomment when InvoicesApplication class will exist

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>com.vrtoonjava.invoices.InvoicesApplication</mainClass>
                </configuration>
            </plugin>
			-->
        </plugins>
    </build>

</project>

自举骆驼

在使用Apache Camel之前,我们需要对其进行一些引导。 首先,我们将创建包com.vrtoonjava.routes ,在其中放置路由配置。 其次,我们将创建InvoicesRouteBuilder类,该类将是配置路由的地方。 因此,像这样创建类:

package com.vrtoonjava.routes;

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class InvoicesRouteBuilder extends RouteBuilder {

    @Override
    public void configure() throws Exception {
		//TODO configure route
	}
}

最后要做的是将Camel插入Spring(Camel将使用Spring作为bean的注册表)。 将文件camel-config.xml添加到您的src / main / resources文件夹中,其中包含以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <routeBuilder ref="invoicesRouteBuilder"/>
    </camelContext>

</beans>

现在,让我们更详细地介绍系统的六个主要组件,并获得实际的代码。

1.发票网关

首先,让我们看一下Invoice的代码-这将是系统中的核心类之一。 我将使用com.vrtoonjava软件包作为根软件包,使用invoicesbanking作为子软件包:

package com.vrtoonjava.invoices;

import com.google.common.base.Objects;

import java.math.BigDecimal;

public class Invoice {

    private final String iban;
    private final String address;
    private final String account;
    private final BigDecimal dollars;

    public Invoice(String iban, String address, String account, BigDecimal dollars) {
        this.iban = iban;
        this.address = address;
        this.account = account;
        this.dollars = dollars;
    }

    public boolean isForeign() {
        return null != iban && !iban.isEmpty();
    }

    public String getAddress() {
        return address;
    }

    public String getAccount() {
        return account;
    }

    public BigDecimal getDollars() {
        return dollars;
    }

    public String getIban() {
        return iban;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("iban", iban)
                .add("address", address)
                .add("account", account)
                .add("dollars", dollars)
                .toString();
    }

}

想象一下,我们正在从另一个系统(数据库,Web服务或其他系统)获取发票,但是我们不想将此部分耦合到集成层。 我们将为此使用网关组件。 Gateway引入了一个契约 ,该契约将客户端代码与集成层分离(在我们的示例中为Apache Camel依赖项)。 让我们看一下InvoiceCollectorGateway的代码:

package com.vrtoonjava.invoices;

import java.util.Collection;

/**
 * Defines a contract that decouples client from the Apache Camel framework.
 */
public interface InvoiceCollectorGateway {

    void collectInvoices(Collection<Invoice> invoices);

}

我们定义了此接口,以使客户仅依赖合同。 实际的实现将是特定于骆驼的,我们可以这样创建它:

package com.vrtoonjava.invoices;

import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CamelInvoiceCollectorGateway implements InvoiceCollectorGateway {

    @Produce(uri = "seda:newInvoicesChannel")
    ProducerTemplate producerTemplate;

    @Override
    public void collectInvoices(Collection<Invoice> invoices) {
        producerTemplate.sendBody(invoices);
    }

}

注意@Produce批注。 此注释告诉Camel,字段producerTemplate是端点seda:newInvoicesChannel 。 当客户端调用collectInvoices方法时,网关将向seda:newInvoicesChannel通道发送一条新消息(包含列表主体)。 这使客户端与消息传递工具脱钩,但是让我们将结果放置到实际的消息传递通道中。

为什么选择SEDA?

通常,在用Java构建消息传递系统时,最终会使用像JMS这样的东西,它提供了许多有用的功能,例如高可靠性或消息持久性。 在本教程中,我们将使用基于SEDA组件的更轻松的替代方法-它使我们能够利用几乎零配置的异步内存中消息传递。

2.发票分割器

从网关,我们向包含发票集合的系统发送一条大消息-换句话说,消息具有“ Collection类型的正文。 当我们要单独处理发票时,我们将从seda:newInvoicesChannel获得结果,并使用分离器组件,该组件将创建多个消息。 这些新消息中的每一个都有一个“发票”类型的正文。 然后,我们将消息放置到新渠道– seda:singleInvoicesChannel 。 这就是我们定义拆分器的方式(将以下代码添加到InvoicesRouteBuilderconfigure方法中):

from("seda:newInvoicesChannel")
        .log(LoggingLevel.INFO, "Invoices processing STARTED")
        .split(body())
        .to("seda:singleInvoicesChannel");

3.过滤一些发票

我们系统的业务用例要求我们仅自动处理发出少于$ 10,000的发票。 为此,我们将介绍一个过滤器组件。 我们将从seda:singleInvoicesChannel抓取消息,对它们应用过滤逻辑,然后将匹配的结果写入新的seda:filteredInvoicesChannel通道。 在Apache Camel中,您可以插入自己的包含过滤逻辑的谓词 。 首先,让我们定义这样的谓词(通过扩展Camel的org.apache.camel.Predicate ):

package com.vrtoonjava.invoices;

import org.apache.camel.Exchange;
import org.apache.camel.Predicate;

public class LowEnoughAmountPredicate implements Predicate {

    public static final int LOW_ENOUGH_THRESHOLD = 10_000;

    @Override
    public boolean matches(Exchange exchange) {
        Invoice invoice = exchange.getIn().getBody(Invoice.class);
        boolean lowEnough = invoice.getDollars().intValue() < LOW_ENOUGH_THRESHOLD;
        System.out.println("Amount of $" + invoice.getDollars()
                + (lowEnough ? " can" : " can not") + " be automatically processed by system");

        return lowEnough;
    }

}

为了简洁起见,我不在本教程中粘贴单元测试–但是,如果您有兴趣, 请继续下载github项目并亲自查看测试

现在我们需要将此谓词连接到我们的路由,因此将以下代码添加到您的configure方法中:

from("seda:singleInvoicesChannel")
        .filter(new LowEnoughAmountPredicate())
        .to("seda:filteredInvoicesChannel");

4.路由发票

到目前为止,我们已经拆分并过滤了一些发票。 现在是时候更仔细地检查每个发票的内容并决定是从当前国家(本地)还是从另一个国家(外国)发行的发票了。 Apache Camel允许使用Java DSL中的choice()方法来定义基于内容的路由器 。 我们甚至可以直接在Java DSL中访问消息的主体并执行一些简单的评估。 将以下代码添加到您的configure方法中(并注意我们如何使用${body.isForeign}标准表达式来访问body):

from("seda:filteredInvoicesChannel")
        .choice()
            .when().simple("${body.isForeign}")
                .to("seda:foreignInvoicesChannel")
            .otherwise()
                .to("seda:localInvoicesChannel");

我们将在本教程第二部分中继续开发此应用程序。


翻译自: https://www.javacodegeeks.com/2013/10/apache-camel-developing-application-from-the-scratch-part-1-2.html

apache camel

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值