Mulesoft 简明教程
MuleSoft - Introduction to Mule ESB
ESB 表示 Enterprise Service Bus ,它基本上是一个中间件工具,用于通过类似于总线的架构将各种应用程序集成在一起。从根本上说,它是一种设计,用于为集成应用程序之间的工作移动提供统一的手段。通过这种方式,在 ESB 架构的帮助下,我们可以通过通信总线连接不同的应用程序,并使它们能够在不相互依赖的情况下进行通信。
ESB stands for Enterprise Service Bus which is basically a middleware tool for integrating various applications together over a bus-like infrastructure. Fundamentally, it is an architecture designed to provide a uniform means of moving work among integrated applications. In this way, with the help of ESB architecture we can connect different applications through a communication bus and enable them to communicate without depending on one another.
Implementing ESB
ESB 架构的主要重点是将系统彼此解耦,并允许它们以稳定且可控的方式进行通信。ESB 的实现可以通过以下方式借助 ‘Bus’ 和 ‘Adapter’ 来完成:
The main focus of ESB architecture is to decouple the systems from each other and allow them to communicate in a steady and controllable way. ESB’s implementation can be done with the help of ‘Bus’ and ‘Adapter’ in the following way −
-
The concept of “bus”, which is achieved through a messaging server like JMS or AMQP, is used to decouple different applications from one another.
-
The concept of “adapter”, responsible for communicating with backend application and transforming data from application format to bus format, is used between applications and bus.
通过总线从一个应用程序传递到另一个应用程序的数据或消息采用规范格式,这意味着将有一个一致的消息格式。
The data or message passing from one application to another through the bus is in a canonical format which means there would be one consistent message format.
适配器还可以执行其他活动,如安全、监视、错误处理和消息路由管理。
The adapter can also perform other activities like security, monitoring, error handling and message routing management.
ESB’s Guiding Principles
我们可以将这些原则称为核心集成原则。它们如下:
We can call these principles as core integration principles. They are as follows −
-
Orchestration − Integration of two or more services to achieve synchronization between data and process.
-
Transformation − Transforming data from canonical format to application specific format.
-
Transportation − Handling protocol negotiation between formats like FTP, HTTP, JMS, etc.
-
Mediation − Providing multiple interfaces to support multiple versions of a service.
-
Non-functional consistency − Providing mechanism for managing transactions and security also.
Need of ESB
ESB 架构使我们能够集成不同的应用程序,其中每个应用程序都可以通过它来通信。以下是在何时使用 ESB 的一些指南 −
ESB architecture enables us to integrate different applications where each application can communicate through it. Following are some guidelines on when to use ESB −
-
Integrating two or more applications − Use of ESB architecture is beneficial when there is a need to integrate two or more services or applications.
-
Integration of more applications in future − Suppose if we want to add more services or applications in future, then it can be easily done with the help of ESB architecture.
-
Using multiple protocols − In case if we need to use multiple protocols like HTTP, FTP, JMS etc., ESB is the right option.
-
Message routing − We can use ESB in case if we require message routing based on message content and other similar parameters.
-
Composition and consumption − ESB can be used if we need to publish services for composition and consumption.
P2P integration vs. ESB integration
随着应用程序数量的增加,摆在开发人员面前的一个大问题是,如何连接不同的应用程序?这种情况可以通过手动编写各种应用程序之间的连接来处理。这称为 point-to-point integration 。
With the increase in number of applications, a big question in front of developers was how to connect different applications? The situation was handled by hand-coding a connection between various application. This is called point-to-point integration.
Rigidity 是点对点集成的最明显的缺点。连接和接口的数量越多,复杂性也会越大。P-2-P 集成的缺点导致了我们使用 ESB 集成。
Rigidity is the most obvious drawback of point-to-point integration. The complexity increases with the increased number of connections and interfaces. The disadvantages of P-2-P integration leads us to ESB integration.
ESB 是用于实现应用程序集成的更灵活的方式。它将每个应用程序功能封装并公开为一组离散的可重用功能。没有任何应用程序直接与其他应用程序集成,取而代之的是通过 ESB 来集成,如下所示 −
ESB is a more flexible approach to application integration. It encapsulates and exposes each application functionality as a set of discrete reusable capabilities. No application directly integrates with other, instead they integrate through an ESB as shown below −
为了管理集成,ESB 具有以下两个组件 −
For managing the integration, ESB has the following two components −
-
Service Registry − Mule ESB has Service Registry/Repository where all the services exposed into the ESB are published and registered. It acts as a point of discovery from where one can consume the services and capabilities of other applications.
-
Centralized Administration − As the name implies, it provides a view of transactional flows of performance of interactions occurring inside the ESB.
ESB Functionality − VETRO 缩写通常用于总结 ESB 的功能。具体如下 −
ESB Functionality − VETRO abbreviation is generally used to summarize the functionality of ESB. It is as follows −
-
V(Validate) − As the name implies, it validates the schema validation. It requires a validating parser and up-to-date schema. One example is an XML document confirming to an up-to-date schema.
-
E(Enrich) − It adds additional data to a message. The purpose is to make message more meaningful and useful to a target service.
-
T(Transform) − It converts the data structure to a canonical format or from a canonical format. Examples are conversion of date/time, currency, etc.
-
*R(*Routing) − It will route the message and act as a gatekeeper of the endpoint of a service.
-
O(Operate) − The main job of this function is to invoke the target service or interacts with the target app. They run at the backend.
VETRO 模式为集成提供了整体灵活性,并确保只有经过验证一致的数据才能在整个 ESB 中路由。
VETRO pattern provides overall flexibility to the integration and ensures that only consistent and validated data will be routed throughout the ESB.
What is Mule ESB?
Mule ESB 是 MuleSoft 提供的轻量级且高度可扩展的基于 Java 的企业服务总线 (ESB) 和集成平台。Mule ESB 使开发人员能够轻松快速地连接应用程序。无论应用程序使用的技术如何,Mule ESB 都能轻松集成应用程序,使它们能够交换数据。Mule ESB 具有以下两个版本−
Mule ESB is a lightweight and highly scalable Java-based enterprise service bus (ESB) and integration platform provided by MuleSoft. Mule ESB allows the developer to connect applications easily and quickly. Regardless of various technologies used by applications, Mule ESB enables easy integration of applications, enabling them to exchange data. Mule ESB has the following two editions −
-
Community Edition
-
Enterprise Edition
Mule ESB 的优势在于,我们可以轻松地从 Mule ESB 社区版升级到 Mule ESB 企业版,因为这两个版本都是基于通用的代码库构建的。
An advantage of Mule ESB is that we can easily upgrade from Mule ESB community to Mule ESB enterprise because both the editions are built on a common code base.
Features & Capabilities of Mule ESB
Mule ESB 具有以下功能−
Following features are possessed by Mule ESB −
-
It has simple drag-and-drop graphical design.
-
Mule ESB is capable of visual data mapping and transformation.
-
User can get the facility of 100s of pre-built certified connectors.
-
Centralized monitoring and administration.
-
It provides robust enterprise security enforcement capabilities.
-
It provides the facility of API management.
-
There is secure Data Gateway for cloud/on-premise connectivity.
-
It provides the service registry where all the services exposed into the ESB are published and registered.
-
Users can have control through a web-based management console.
-
Rapid debugging can be performed using service flow analyzer.
MuleSoft - The Mule Project
Mule项目的动机如下−
The motivations behind the Mule project were −
-
to make things simpler for the programmers,
-
the need of lightweight and modular solution that could scale from an application-level messaging framework to an enterprise-wide highly distributable framework.
Mule ESB的设计基于事件驱动和以编程为基础的框架。它基于事件驱动,因为它结合了消息的统一表示方式,并且可以通过可插入模块进行扩展。它以编程为基础,因为程序员可以轻松地植入一些附加行为,例如特定消息处理或自定义数据转换。
Mule ESB is designed as an event-driven as well as programmatic framework. It is event-driven because it is combined with unified representation of messages and can be expandable with pluggable modules. It is programmatic because programmers can easily implant some additional behaviors such as specific message processing or custom data transformation.
History
Mule项目的背景如下−
The historical perspective of Mule project is as follows −
SourceForge project
Mule项目始于2003年4月的SourceForge项目,两年后其第一版发布并转移到CodeHaus。通用消息对象(UMO)API是其架构的核心。UMO API背后的理念是统一逻辑,同时使它们与底层传输保持隔离。
The Mule project was started as the SourceForge project in April 2003, and after 2 years its first version was released and moved to CodeHaus. Universal Message Object (UMO) API was at the core of its architecture. The idea behind UMO API was to unify the logic while keeping them isolated from the underlying transports.
Version 1.0
它于2005年4月发布,其中包含许多传输。随后许多其他版本的主要重点是调试和添加新功能。
It was released in April 2005 containing numerous transports. The key focus of many other versions followed by it, was on debugging and adding new features.
Version 2.0 (Adoption of Spring 2)
Spring 2作为配置和连接框架被采纳到Mule 2中,但它被证明是一次重大的检修,因为缺少对必需的XML配置的表达力。当基于XML架构的配置被引入Spring 2时,此问题得到解决。
Spring 2 as configuration and wiring framework was adopted in Mule 2 but it proved to be a major over-haul because of the lack of expressiveness of the required XML configuration. This issue was resolved when XML Schema-based configuration has been introduced in Spring 2.
Competitors of Mule ESB
以下是Mule ESB的主要竞争对手−
Following are some of the major competitors of Mule ESB −
-
WSO2 ESB
-
Oracle Service Bus
-
WebSphere Message Broker
-
Aurea CX Platform
-
Fiorano ESB
-
WebSphere DataPower Gateway
-
Workday Business Process Framework
-
Talend Enterprise Service Bus
-
JBoss Enterprise Service Bus
-
iWay Service Manager
Mule’s Core Concept
如上所述,Mule ESB是一个基于Java的轻量级且高度可扩展的企业服务总线(ESB)和集成平台。无论应用程序使用何种技术,Mule ESB都能轻松集成应用程序,使其能够交换数据。在本节中,我们将讨论Mule的核心概念,以实现这种集成。
As discussed, Mule ESB is a lightweight and highly scalable Java-based enterprise service bus (ESB) and integration platform. Regardless of various technologies used by applications, Mule ESB enables easy integration of applications, enabling them to exchange data. In this section, we will discuss about Mule’s core concept coming into play to make such integration happen.
为此,我们需要了解其架构及构建块。
For this, we need to understand its architecture as well as building blocks.
Architecture
Mule ESB的架构具有三层,即传输层、集成层和应用程序层,如下图所示−
The architecture of Mule ESB has three layers namely, Transport layer, Integration layer and Application layer as shown in the following diagram −
通常,可以执行以下三类任务来配置和定制Mule部署−
Generally, there are following three types of tasks that can be performed to configure and customize Mule deployment −
Service Component Development
此项任务涉及开发或重复使用现有的POJO或Spring Bean。POJO是一个带有属性的类,该属性生成get和set方法、云连接器。另一方面,Spring Bean包含用于丰富消息的业务逻辑。
This task involves development or re-using the existing POJOs, or Spring Beans. POJOs is a class with attributes that generates the get and set methods, cloud connectors. On the other hand, Spring Beans contains the business logic to enrich messages.
Service Orchestration
此项任务基本提供了涉及配置消息处理器、路由器、转换器和过滤器的服务中介。
This task basically provides the service mediation that involves configuring the message processor, routers, transformers and filters.
Integration
Mule ESB的最重要任务是集成各种应用程序,无论它们使用的协议如何。为此,Mule提供了传输方法,允许在各种协议连接器上接收和分发消息。Mule支持许多现有的传输方法,或者我们还可以使用自定义传输方法。
The most important task of Mule ESB is the integration of various applications regardless of the protocols they are using. For this purpose, Mule provides transport methods that allow receiving and dispatching the messages on various protocol connectors. Mule supports many existing transport methods, or we may also use a custom transport method.
Building Blocks
Mule配置具有以下构建块−
Mule configuration has the following building blocks −
Spring beans
Spring bean 的主要用途是构建服务组件。构建 Spring 服务组件后,如果用户没有配置文件,可以通过配置文件或手动定义服务组件。
The main use of Spring beans is to construct service component. After constructing spring service component, we can define it through a configuration file or manually, in case you do not have configuration file.
Agents
它最初是 Anypoint Studio 中在 Mule Studio 之前创建的服务。一旦服务器启动,将会创建一个代理,一旦服务器停止,将会销毁该代理。
It is basically a service created in Anypoint Studio before Mule Studio. An agent is created once you start a server and will be destroyed once you stop the server.
Connector
它是一个软件组件,配置为特定于协议的参数。它主要用于控制协议的使用。例如,JMS 连接器配置有 Connection ,该连接器共享在负责实际通信的不同实体之间。
It is a software component configured with the parameters that are specific to protocols. It is mainly used for controlling the usage of a protocol. For example, a JMS connector is configured with a Connection and this connector will be shared among various entities in charge of actual communication.
Global Configuration
顾名思义,这个构建块用于设置全局属性和设置。
As the name implies, this building block is used to set the global properties and settings.
Global Endpoints
它可以在“全局元素”选项卡中使用,该选项卡可以在流程中多次使用:
It can be used in Global Elements tab which can be used as many times in a flow −
Global Message Processor
顾名思义,它观察或修改消息或消息流。转换器和过滤器是全局消息处理程序的示例。
As the name implies, it observes or modifies a message or message flow. Transformers and filters are the examples of Global Message Processor.
Transformers - 转换器的主要工作是将数据从一种格式转换成另一种格式。可以在全局中定义,并可以在多个流程中使用。
Transformers − The main job of a transformer is to convert data from one format to another. It can be defined globally and can be used in multiple flows.
Filters - 它是一个过滤器,将决定应该处理哪条 Mule 消息。过滤器基本上指定消息必须满足的条件,然后才能处理并路由到服务。
Filters − It is the filter that will decide which Mule message should be processed. Filter basically specifies the conditions that must be met for a message to be processed and routed to a service.
Models
与代理相反,它是工作室中创建的服务的逻辑分组。我们有权启动和停止特定模型中的所有服务。
In contrast to Agents, it is a logical grouping of services which are created in studio. We have the liberty to start and stop all the services inside a specific model.
Services - 服务是封装业务逻辑或组件的服务。它还专门为该服务配置了路由器、端点、转换器和过滤器。
Services − Services are the one that wrap our business logic or components. It also configures Routers, Endpoints, transformers and filters specifically for that service.
Endpoints - 可以将其定义为一个对象,服务将在其上入站(接收)和出站(发送)消息。服务通过端点连接。
Endpoints − It may be defined as an object on which services will inbound (receive) and outbound (send) messages. Services are connected through endpoints.
Mule Message Structure
Mule 消息完全包装在 Mule 消息对象中,是通过 Mule 流程传递到应用程序中的数据。Mule 消息的结构在以下图表中显示:
A Mule message, totally wrapped under Mule Message Object, is the data that passes through applications via Mule flows. The structure Mule’s message is shown in the following diagram −
正如上述图表中所示,Mule 消息包含两个主要部分:
As seen in the above diagram, Mule Message consists of two main parts −
Header
它只不过是消息的元数据,由以下两个属性进一步表示:
It is nothing but the metadata of the message which is further represented by the following two properties −
Inbound Properties - 这些属性由消息源自动设置。它们不能由用户操作或设置。本质上,入站属性是不可变的。
Inbound Properties − These are the properties which are automatically set by the message source. They cannot be manipulated or set by the user. In nature, inbound properties are immutable.
Outbound Properties - 这些属性是包含元数据的属性,比如入站属性,可以在流程期间设置。它们可以由 Mule 自动设置,也可以由用户手动设置。本质上,出站属性是可变的。
Outbound Properties − These are the properties that contain metadata like an inbound property and can set during the course of flow. They can be set automatically by Mule or manually by a user. In nature, outbound properties are mutable.
当消息通过一个流程的出站端点通过传输转到另一个流程的入站端点时,出站属性将变为入站属性。
Outbound properties become inbound properties when the message passes from the outbound endpoint of one flow to the inbound endpoint of a different flow via a transport.
当消息通过 flow-ref 而不是连接器转到新流程时,出站属性仍保持出站属性。
Outbound properties remain outbound properties when the message is passed to a new flow via a flow-ref rather than a connector.
Payload
消息对象承载的实际业务消息称为有效负载。
The actual business message carried by message object is called payload.
Variables
它可以定义为关于消息的用户自定义元数据。基本上,变量是有关于由正在处理该消息的应用程序使用的消息的暂时信息片段。它不应该与消息一起传递到其目的地。它们有以下三种类型 −
It may be defined as the user-defined metadata about a message. Basically, variables are temporary pieces of information about a message used by the application that is processing it. It is not meant to be passed along with the messages to its destination. They are of three types as given below −
Flow variables − 这些变量仅适用于它们存在的流。
Flow variables − These variables apply only to the flow in which they exist.
Session variables − 这些变量适用于同一应用程序中的所有流。
Session variables − These variables apply across all the flows within the same application.
Record variables − 这些变量仅适用于作为一个批处理的一部分处理的记录。
Record variables − These variables apply only to records processed as part of a batch.
MuleSoft - Mule in Our Machine
在前面章节中,我们了解了 Mule ESB 的基础知识。在本章节中,我们将了解如何安装和配置它。
In the previous chapters, we have learnt the basics of Mule ESB. In this chapter, let us learn how to install and configure it.
Prerequisites
在计算机上安装 Mule 之前,我们需要满足以下先决条件−
We need to satisfy the following prerequisites before installing Mule on our computer −
Java Development Kit (JDK)
在安装 MULE 之前,请验证您的系统上是否支持 Java 版本。建议使用 JDK 1.8.0 在您的系统上成功安装 Mule。
Before installing MULE, verify that you have supported version of Java on your system. JDK 1.8.0 is recommended to successfully install Mule on your system.
Operating System
Mule 支持以下操作系统−
Following operating systems are supported by Mule −
-
MacOS 10.11.x
-
HP-UX 11iV3
-
AIX 7.2
-
Windows 2016 Server
-
Windows 2012 R2 Server
-
Windows 10
-
Windows 8.1
-
Solaris 11.3
-
RHEL 7
-
Ubuntu Server 18.04
-
Linux Kernel 3.13+
Database
由于 Mule Runtime 以独立服务器的形式运行,因此不需要应用程序服务器或数据库。但是,如果我们需要访问数据存储或想要使用应用程序服务器,可以使用以下受支持的应用程序服务器或数据库−
An application server or database is not required as the Mule Runtime runs as a standalone server. But if we need to access a data store or want to use an application server, following supported application servers or databases can be used −
-
Oracle 11g
-
Oracle 12c
-
MySQL 5.5+
-
IBM DB2 10
-
PostgreSQL 9
-
Derby 10
-
Microsoft SQL Server 2014
System Requirements
在系统上安装 Mule 之前,它必须满足以下系统要求−
Before installing Mule on your system, it must fulfil the following system requirements −
-
At least 2 GHz CPU or 1 Virtual CPU in virtualized environments
-
Minimum 1 GB RAM
-
Minimum 4 GB storage
Download Mule
要下载 Mule 4 二进制文件,请点击链接 https://www.mulesoft.com/lp/dl/mule-esb-enterprise ,它会将您引导至 MuleSoft 的官方网页,如下所示−
To download Mule 4 binary file, click on the link https://www.mulesoft.com/lp/dl/mule-esb-enterprise and it will lead you to the official web page of MuleSoft as follows −
通过提供必要的信息,您会以 Zip 格式获取 Mule 4 二进制文件。
By providing the necessary details, you can get the Mule 4 binary file in Zip format.
Install and Run Mule
现在在下载完 Mule 4 二进制文件后,解压缩它并设置一个名为 MULE_HOME 的环境变量,用于提取的文件夹中的 Mule 目录。
Now after downloading the Mule 4 binary file, unzip it and set an environment variable called MULE_HOME for the Mule directory inside the extracted folder.
例如,Windows 和 Linux/Unix 环境中的环境变量,可以在 Downloads 目录中设置为版本 4.1.5,如下所示−
For example, the environment variable, on Windows and Linux/Unix environments, can be set for version 4.1.5 in the Downloads directory as follows −
Unix/Linux Environments
$ export MULE_HOME=~/Downloads/mule-enterprise-standalone-4.1.5/
现在,要测试 Mule 是否在您的系统中无任何错误地运行,请使用以下命令−
Now, for testing whether Mule is running in your system without any error, use the following commands −
Unix/Linux Environments
$ $MULE_HOME/bin/mule
以上命令将在前台模式下运行 Mule。如果 Mule 正在运行,我们无法在终端上发布任何其他命令。在终端中按 ctrl-c 命令将停止 Mule。
The above commands will run Mule in the foreground mode. If Mule is running, we cannot issue any other commands on the terminal. Pressing ctrl-c command in the terminal, will stop Mule.
Start Mule Services
我们还可以将 Mule 作为 Windows 服务和 Linux/Unix 后台程序启动。
We can start Mule as a Windows Service and as a Linux/Unix Daemon also.
Mule as a Windows Service
若要作为 Windows 服务运行 Mule,我们需要按照如下步骤 −
To run Mule as a Windows service, we need to follow the below steps −
Step 1 - 首先,借助以下命令安装它 −
Step 1 − First, install it with the help of following command −
$ $MULE_HOME\bin\mule.bat install
Step 2 - 安装完成后,借助以下命令,我们可以将 mule 作为 Windows 服务运行:
Step 2 − Once installed, we can run mule as a Windows service with the help of the following command:
$ $MULE_HOME\bin\mule.bat start
Mule as a Linux/Unix Daemon
若要将 Mule 作为 Linux/Unix 守护进程运行,我们需要按照以下步骤操作:
To run Mule as a Linux/Unix Daemon, we need to follow the below steps −
Step 1 - 在安装它的帮助下使用以下命令进行安装:
Step 1 − Install it with the help of the following command −
$ $MULE_HOME/bin/mule install
Step 2 - 安装后,我们可以在以下命令的帮助下将 mule 作为 Windows 服务运行:
Step 2 − Once installed, we can run mule as a Windows service with the help of following command −
$ $MULE_HOME/bin/mule start
Example
以下示例将 Mule 作为 Unix 守护进程启动:
The following example starts Mule as a Unix Daemon −
$ $MULE_HOME/bin/mule start
MULE_HOME is set to ~/Downloads/mule-enterprise-standalone-4.1.5
MULE_BASE is set to ~/Downloads/mule-enterprise-standalone-4.1.5
Starting Mule Enterprise Edition...
Waiting for Mule Enterprise Edition.................
running: PID:87329
Deploy Mule Apps
我们可以借助以下步骤部署我们的 Mule 应用程序:
We can deploy our Mule apps with the help of following steps −
Step 1 - 首先,启动 Mule。
Step 1 − First, start Mule.
Step 2 - Mule 启动后,我们可以通过将 JAR 包文件移到 apps 中的 $MULE_HOME 目录来部署我们的 Mule 应用程序。
Step 2 − Once Mule starts, we can deploy our Mule applications by moving our JAR package files to the apps directory in $MULE_HOME.
Stop Mule Services
我们可以使用 stop 命令来停止 Mule。例如,以下示例将 Mule 作为 Unix 守护进程启动:
We can use stop command to stop Mule. For example, the following example starts Mule as a Unix Daemon −
$ $MULE_HOME/bin/mule stop
MULE_HOME is set to /Applications/mule-enterprise-standalone-4.1.5
MULE_BASE is set to /Applications/mule-enterprise-standalone-4.1.5
Stopping Mule Enterprise Edition...
Stopped Mule Enterprise Edition.
我们还可以使用 remove 命令从我们的系统中删除 Mule 服务或守护进程。以下示例将 Mule 作为 Unix 守护进程删除:
We can also use remove command to remove the Mule Service or Daemon from our system. The following example removes Mule as a Unix Daemon −
$ $MULE_HOME/bin/mule remove
MULE_HOME is set to /Applications/mule-enterprise-standalone-4.1.5
MULE_BASE is set to /Applications/mule-enterprise-standalone-4.1.5
Detected Mac OSX:
Mule Enterprise Edition is not running.
Removing Mule Enterprise Edition daemon...
MuleSoft - Anypoint Studio
MuleSoft 的 Anypoint Studio 是一个用户友好的 IDE (integration development environment) ,用于设计和测试 Mule 应用程序。这是一个基于 Eclipse 的 IDE。我们可以轻松地从 Mule Palette 中拖动连接器。换句话说,Anypoint Studio 是一个基于 Eclipse 的 IDE,用于开发流等。
MuleSoft’s Anypoint Studio is a user-friendly IDE (integration development environment) used for designing and testing Mule applications. It is an Eclipse-based IDE. We can easily drag Connectors from the Mule Palette. In other words, Anypoint Studio is an Eclipse based IDE for development of flow, etc.
Prerequisites
在所有操作系统(即 Windows、Mac 和 Linux/Unix)上安装 Mule 之前,我们需要满足以下先决条件。
We need to satisfy following prerequisites before installing Mule on all OS, i.e., Windows, Mac and Linux/Unix.
Java Development Kit (JDK) − 在安装 Mule 之前,检查你的系统是否拥有支持的 Java 版本。建议使用 JDK 1.8.0 在系统上成功安装 Anypoint。
Java Development Kit (JDK) − Before installing Mule, verify that you have supported version of Java on your system. JDK 1.8.0 is recommended to successfully install Anypoint on your system.
Downloading and Installing Anypoint Studio
在不同的操作系统上下载并安装 Anypoint Studio 的步骤可能有所不同。接下来,以下是适用于各种操作系统的 Anypoint Studio 下载和安装步骤 −
The procedure to download and install Anypoint Studio on different operating systems may vary. Next, there are steps to be followed for downloading and installing Anypoint Studio on various operating systems −
On Windows
要在 Windows 上下载并安装 Anypoint Studio,我们需要执行以下步骤 −
To download and install Anypoint Studio on Windows, we need to follow the steps below −
Step 1 − 首先,单击链接 https://www.mulesoft.com/lp/dl/studio 并从下拉列表中选择 Windows 操作系统下载该工作室。
Step 1 − First, click on the link https://www.mulesoft.com/lp/dl/studio and choose the Windows operating system from top-down list to download the studio.
Step 2 − 现在,将其提取到 ‘C:\’ 根文件夹。
Step 2 − Now, extract it into the ‘C:\’ root folder.
Step 3 − 打开提取的 Anypoint Studio。
Step 3 − Open the extracted Anypoint Studio.
Step 4 − 要接受默认工作区,请单击确定。首次加载时,您将收到欢迎消息。
Step 4 − For accepting the default workspace, click OK. You will get a welcome message when it loads for the first time.
Step 5 − 现在,单击入门按钮以使用 Anypoint Studio。
Step 5 − Now, click on Get Started button to use Anypoint Studio.
On OS X
要在 OS X 上下载并安装 Anypoint Studio,我们需要执行以下步骤 −
To download and install Anypoint Studio on OS X, we need to follow the steps below −
Step 1 − 首先,单击链接 https://www.mulesoft.com/lp/dl/studio 并下载该工作室。
Step 1 − First, click on the link https://www.mulesoft.com/lp/dl/studio and download the studio.
Step 2 − 现在,将其提取。如果你正在使用 OS 版本 Sierra,请务必在启动之前将提取的 App 移至 /Applications folder 。
Step 2 − Now, extract it. In case if you are using OS version Sierra, make sure to move the extracted app to /Applications folder before launching it.
Step 3 − 打开提取的 Anypoint Studio。
Step 3 − Open the extracted Anypoint Studio.
Step 4 − 要接受默认工作区,请单击确定。首次加载时,您将收到欢迎消息。
Step 4 − For accepting the default workspace, click OK. You will get a welcome message when it loads for the first time.
Step 5 − 现在,单击 Get Started 按钮以使用 Anypoint Studio。
Step 5 − Now, click on Get Started button to use Anypoint Studio.
如果你打算对工作区使用自定义路径,请注意 Anypoint Studio 不会展开 Linux/Unix 系统中使用的波浪号 (~)。因此,建议在定义工作区时使用绝对路径。
If you are going to use custom path to your workspace, then please note that Anypoint Studio does not expand the ~ tilde used in Linux/Unix systems. Hence, it is recommended to use the absolute path while defining the workspace.
On Linux
要在 Linux 上下载并安装 Anypoint Studio,我们需要执行以下步骤 −
To download and install Anypoint Studio on Linux, we need to follow the steps below −
Step 1 − 首先,单击链接 https://www.mulesoft.com/lp/dl/studio 并从下拉列表中选择 Linux 操作系统下载该工作室。
Step 1 − First, click on the link https://www.mulesoft.com/lp/dl/studio and choose the Linux operating system from top-down list to download the studio.
Step 2 − 现在,将其提取。
Step 2 − Now, extract it.
Step 3 − 接下来,打开提取的 Anypoint Studio。
Step 3 − Next, open the extracted Anypoint Studio.
Step 4 − 要接受默认工作区,请单击确定。首次加载时,您将收到欢迎消息。
Step 4 − For accepting the default workspace, click OK. You will get a welcome message when it loads for the first time.
Step 5 − 现在,单击入门按钮以使用 Anypoint Studio。
Step 5 − Now, click on Get Started button to use Anypoint Studio.
如果你打算对工作区使用自定义路径,请注意 Anypoint Studio 不会展开 Linux/Unix 系统中使用的波浪号 (~)。因此,建议在定义工作区时使用绝对路径。
If you are going to use custom path to your workspace, then please note that Anypoint Studio does not expand the ~ tilde used in Linux/Unix systems. Hence, it is recommended to use the absolute path while defining the workspace.
还建议安装 GTK 版本 2 来在 Linux 中使用完整的工作室主题。
It is also recommended to install GTK version 2 to use complete Studio Themes in Linux.
Features of Anypoint Studio
以下是 Anypoint studio 增强 Mule 应用程序构建过程中的生产力的某些功能
Following are some features of Anypoint studio enhancing the productivity while building Mule applications −
-
It provides an instant run of Mule application inside a local runtime.
-
Anypoint studio gives us visual editor for configuring API definition files and Mule domains.
-
It has embedded unit testing framework enhancing the productivity.
-
Anypoint studio provides us the Built-in support to deploy to CloudHub.
-
It has the facility to integrate with Exchange for importing templates, examples, definitions and other resources from other Anypoint Platform organization.
MuleSoft - Discovering Anypoint Studio
Anypoint Studio 编辑器帮助我们设计应用程序、API、属性和配置文件。除了设计之外,它还帮助我们编辑它们。为此,我们有 Mule 配置文件编辑器。要打开此编辑器,请双击 /src/main/mule 中的应用程序 XML 文件。
Anypoint Studio editors help us design our applications, APIs, properties and configuration files. Along with designing, it also helps us to edit them. We have the Mule configuration file editor for this purpose. To open this editor, double-click on the application XML file in /src/main/mule.
要使用我们的应用程序,我们在 Mule 配置文件编辑器下有以下三个选项卡。
To work with our application, we have the following three tabs under Mule Configuration file editor.
The Message Flow tab
此选项卡提供了工作流的可视化表示。它基本上包含一个画布,帮助我们直观地检查我们的流。如果您想将 Mule Palette 中的事件处理器添加到画布中,只需拖放,它就会反映在画布中。
This tab gives a visual representation of work flow. It basically contains a canvas that helps us check our flows visually. If you want to add Event Processors from the Mule Palette into the canvas, then just drag and drop and it will reflect in the canvas.
通过单击事件处理器,您可以获得 Mule 属性视图,其中包含所选处理器的属性。我们也可以编辑它们。
By clicking on an Event Processor, you can get the Mule Properties View with the attributes for the selected processor. We can also edit them.
The Global Elements tab
此选项卡包含模块的全局 Mule 配置元素。在此选项卡下,我们可以创建、编辑或删除配置文件。
This tab contains the global Mule configuration elements for the modules. Under this tab we can create, edit or delete configuration files.
The Configuration XML tab
顾名思义,它包含定义 Mule 应用程序的 XML。您在此处所做的所有更改都将反映在画布中以及消息流选项卡下事件处理器的属性视图中。
As the name implies, it contains the XML that defines your Mule application. All the changes you do here will reflect in the canvas as well as the properties view of event processor under the Message Flow tab.
Views
对于活动编辑器,Anypoint studio 为我们提供了项目元数据的图形表示,以及视图中包含的属性。用户可以在 Mule 项目中移动、关闭和添加视图。以下是 Anypoint Studio 中的一些默认视图 −
For the active editor, Anypoint studio gives us the graphical representation of our project metadata, properties with the help of views. A user can move, close as well as add views in the Mule project. Following are some default views in Anypoint studio −
Package Explorer
Package Explorer 视图的主要任务是显示 Mule 项目中包含的项目文件夹和文件。我们可以通过单击它旁边的箭头来展开或收缩 Mule 项目文件夹。可以通过双击打开文件夹或文件。看看它的截图 −
The main task of Package Explorer view is to display the project folders and files consisted in a Mule project. We can expand or contract the Mule project folder by clicking on the arrow next to it. A folder or file can be opened by double clicking it. Have a look at its screenshot −
Mule Palette
Mule Palette 视图显示了事件处理器,如范围、过滤器和流控制路由器,以及模块及其相关操作。Mule Palette 视图的主要任务如下 −
Mule Palette view shows the event processors like scopes, filters, and flow control routers along with modules and their related operations. The main tasks of Mule Palette view are as follows −
-
This view helps us to manage the modules and connectors in our project.
-
We can also add new elements from Exchange.
看看它的截图 −
Have a look at its screenshot −
Mule Properties
顾名思义,它允许我们编辑画布中当前所选模块的属性。Mule 属性视图包括以下内容:
As the name implies, it allows us to edit the properties of the module currently selected in our canvas. Mule Properties view includes the following −
-
DataSense Explorer that supplies real-time information about the data structure of our payload.
-
Inbound and outbound properties, if available or variables.
以下是屏幕截图:
Below is the screenshot −
Console
每当我们创建或运行 Mule 应用程序时,嵌入式 Mule 服务器都会显示一个事件列表和问题列表(如果有的),由 Studio 报告。控制台视图包含该嵌入式 Mule 服务器的控制台。看看其屏幕截图:
Whenever we create or run the Mule application, embedded Mule server displays a list of events and problems, if any, reported by Studio. Console view contains the console of that embedded Mule server. Have a look at its screenshot −
Problems View
我们在处理 Mule 项目时可能会遇到许多问题。所有这些问题都显示在“问题”视图中。以下是屏幕截图
We can encounter many issues while working on our Mule Project. All those issues are displayed in the Problems view. Below is the screenshot
Perspectives
在 Anypoint Studio 中,它是一个按指定方式排列的视图和编辑器的集合。Anypoint Studio 中有两种透视图:
In Anypoint Studio, it is a collection of views and editors in a specified arrangement. There are two kinds of perspectives in Anypoint Studio −
Mule Design Perspective - 这是我们在 Studio 中获得的默认透视图。
Mule Design Perspective − It is the default perspective we get in Studio.
Mule Debug Perspective - Anypoint Studio 提供的另一个透视图是 Mule 调试透视图。
Mule Debug Perspective − Another perspective supplied by Anypoint Studio is Mule Debug Perspective.
另一方面,我们还可以创建自己的透视图,并可以添加或删除任何默认视图。
On the other hand, we can also create our own perspective and can add or remove any of the default views.
MuleSoft - Creating First Mule Application
在本章中,我们将在 MuleSoft 的 Anypoint Studio 中创建我们的第一个 Mule 应用程序。要创建它,首先我们需要启动 Anypoint Studio。
In this chapter we are going to create our first Mule application in MuleSoft’s Anypoint Studio. For creating it, first we need to launch Anypoint Studio.
Launching Anypoint Studio
单击 Anypoint Studio 以启动它。如果您是第一次启动它,那么您将看到以下窗口−
Click on Anypoint Studio to launch it. If you are launching it for first time, then you will see the following window −
User Interface of Anypoint Studio
一旦您单击“转到工作区”按钮,它将引导您转到 Anypoint Studio 的用户界面如下所示−
Once you Click on the Go to Workspace button, it will lead you to the user interface of Anypoint Studio as follows −
Steps for Creating Mule Application
要创建 Mule 应用程序,请按照以下步骤操作−
In order to create your Mule application, follow the below steps −
Creating New Project
创建 Mule 应用程序的第一步是创建一个新项目。它可以通过按照 FILE → NEW → Mule Project 中所示的路径完成,如下所示−
The very first step for creating Mule application is to create a new project. It can be done by following the path FILE → NEW → Mule Project as shown below −
Naming the Project
按照上述说明,在单击“新建 Mule 项目”之后,将打开一个新窗口,询问项目名称和其他规范。输入项目名称“ TestAPP1 ”,然后单击完成按钮。
After clicking on the new Mule Project, as described above, it will open a new window asking for the project name and other specifications. Give the name of the Project, ‘TestAPP1’ and then click on the finish button.
单击完成按钮后,将打开为 MuleProject 建立的工作区,即 ‘TestAPP1’ 。您可以看到前一章中描述的所有 Editors 和 Views 。
Once you click on the Finish Button, it will open the workspace built for your MuleProject namely ‘TestAPP1’. You can see all the Editors and Views described in the previous chapter.
Configuring the Connector
在此,我们将为 HTTP Listener 构建一个简单的 Mule 应用程序。为此,我们需要从 Mule Palette 拖动 HTTP Listener 连接器并将其放到工作区,如下所示 −
Here, we are going to build a simple Mule application for HTTP Listener. For this, we need to drag the HTTP Listener connector from Mule Palette and drop it to the workspace as shown below −
现在,我们需要配置它。如上所示,在基本设置下,单击连接器配置之后的绿色 + 号。
Now, we need to configure it. Click on the green color + sign after Connector configuration under Basic Settings as shown above.
单击确定后,将转到 HTTP Listener 属性页面。现在我们需要在常规选项卡下提供路径。在此特定示例中,我们已 /FirstAPP 提供为路径名称。
On clicking ok, it will take you back on HTTP Listener property page. Now we need to provide the path under General Tab. In this particular example, we have provided /FirstAPP as path name.
Configuring Set Payload Connector
现在,我们需要使用 Set Payload 连接器。我们还需要在设置选项卡下提供其值,如下所示 −
Now, we need to take a Set Payload connector. We also need to give its value under Settings tab as follows −
This is my first Mule Application ,是本示例中提供的名称。
This is my first Mule Application, is the name provided in this example.
Running Mule Application
现在,将其保存并单击 Run as Mule Application ,如下所示 −
Now, save it and click Run as Mule Application as shown below −
我们可以在控制台中进行检查,以下是其部署应用程序的方式 −
We can check it under Console which deploys the application as follows −
它显示您已成功构建您的第一个 Mule 应用程序。
It shows that you have successfully built your first Mule Application.
Verifying Mule Application
现在,我们需要测试我们的应用程序是否正在运行。 Go to POSTMAN ,一个 Chrome 应用程序并输入 URL: http:/localhost:8081 。它显示我们构建 Mule 应用程序时提供的消息,如下所示:-
Now, we need to test whether our app is running or not. Go to POSTMAN, a Chrome app and enter the Url: http:/localhost:8081. It shows the message we have provided while building Mule application as shown below −
MuleSoft - DataWeave Language
DataWeave 基本上是一种 MuleSoft 表达式语言。它主要用于访问和转换通过 Mule 应用程序接收的数据。Mule 运行时负责运行 Mule 应用程序中的脚本和表达式,DataWeave 与 Mule 运行时紧密集成。
DataWeave is basically a MuleSoft expression language. It is mainly used for accessing and transforming the data received through a Mule application. Mule runtime is responsible for running the script and expressions in our Mule application, DataWeave is strongly integrated with Mule runtime.
Features of DataWeave Language
以下是 DataWeave 语言的一些重要特性:-
Following are some important features of DataWeave language −
可以非常轻松地将数据从一种格式转换为另一种格式。例如,我们可以将 application/json 转换为 application/xml。输入负载如下:-
Data can be transformed from one format to another very easily. For example, we can transform application/json to application/xml. The input payload is as follows −
{
"title": "MuleSoft",
"author": " tutorialspoint.com ",
"year": 2019
}
以下是用于转换的 DataWeave 代码:-
Following is the code in DataWeave for transform −
%dw 2.0
output application/xml
---
{
order: {
'type': 'Tutorial',
'title': payload.title,
'author': upper(payload.author),
'year': payload.year
}
}
接下来, output 负载如下:-
Next, the output payload is as follows −
<?xml version = '1.0' encoding = 'UTF-8'?>
<order>
<type>Tutorial</type>
<title>MuleSoft</title>
<author>tutorialspoint.com</author>
<year>2019</year>
</order>
转换组件可以用来创建可以执行简单和复杂数据转换的脚本。
The transform component can be used for creating scripts that performs both simple as well as complex data transformations.
由于大多数 Mule 消息处理程序支持 DataWeave 表达式,因此我们可以在 Mule 事件所需的各个部分访问和使用核心 DataWeave 功能。
We can access and use core DataWeave functions on parts of the Mule event that we need as most of the Mule message processors support DataWeave expressions.
Prerequisites
在我们计算机上使用 DataWeave 脚本之前,我们需要满足以下前提条件:-
We need to satisfy the following prerequisites before using DataWeave scripts on our computer −
-
Anypoint Studio 7 is required to use Dataweave scripts.
-
After installing Anypoint Studio, we need to set up a project with a Transform Message component in order to use DataWeave scripts.
Steps for Using DataWeave Script with Example
为了使用 DataWeave 脚本,我们需要按照以下步骤进行操作:
In order to use DataWeave scrip, we need to follow the steps below −
Step 1
Step 1
首先,我们必须使用 File → New → Mule Project 设置一个新项目,就像我们上一章中所做的一样。
First, we need to set up a new project, as we did in the previous chapter, by using File → New → Mule Project.
Step 2
Step 2
接下来,我们需要提供项目名称。对于该示例,我们指定了名称 Mule_test_script 。
Next, we need to provide the name of the project. For this example, we are giving the name, Mule_test_script.
Step 3
Step 3
现在,我们需要将 Transform Message component 从 Mule Palette tab 拖动到 canvas 中。如下所示:
Now, we need to drag the Transform Message component from Mule Palette tab into canvas. It is shown as below −
Step 4
Step 4
接下来,在 Transform Message component 选项卡中,单击预览以打开预览窗格。我们可以通过单击 Preview 旁边的空白矩形来展开源代码区域。
Next, in the Transform Message component tab, click on Preview to open Preview pane. We can expand the source code area by clicking the empty rectangle next to Preview.
Step 5
Step 5
现在,我们可以开始使用 DataWeave 语言进行脚本编写。
Now, we can start scripting with DataWeave language.
Example
以下是将两个字符串连接成一个字符串的简单示例:
Following is the simple example of concatenating two strings into one −
上述 DataWeave 脚本带有键值对 ({ myString: ("hello" ++ "World") }) ,它会将两个字符串连接成一个字符串。
The above DataWeave script is having a key-value pair ({ myString: ("hello" ++ "World") }) which will concatenate two strings into one.
MuleSoft - Message Processor & Script Components
脚本模块让用户可以在 Mule 中使用脚本语言。简而言之,脚本模块可以交换用脚本语言编写的自定义逻辑。脚本可以用作实施或转换器。它们可用于表达式评估,即,用于控制消息路由。
The scripting modules facilitate users to use scripting language in Mule. In simple words, the scripting module can exchange custom logic written in scripting language. Scripts can be used as Implementations or transformers. They can be used for expression evaluation, i.e., for controlling message routing.
Mule 支持以下脚本语言:
Mule has the following supported scripting languages −
-
Groovy
-
Python
-
JavaScript
-
Ruby
How to Install Scripting Modules?
事实上,Anypoint Studio 随脚本模块一起提供。如果您在 Mule Palette 中找不到该模块,则可以使用 +Add Module 添加该模块。添加后,我们可以在 Mule 应用程序中使用脚本模块操作。
Actually, Anypoint Studio comes with the scripting modules. If you do not find the module in Mule Palette, then it can be added by using +Add Module. After adding, we can use the scripting module operations in our Mule application.
Implementing Example
正如所讨论的,我们需要将该模块拖放到画布中以创建工作区并在应用程序中使用它。以下是一个示例:
As discussed, we need to drag and drop the module into canvas for creating workspace and use it in our application. Following is an example of it −
我们已经知道如何配置 HTTP Listener 组件;因此,我们将讨论配置脚本模块。我们需要按照以下编写步骤配置脚本模块:
We already know how to configure the HTTP Listener component; hence we are going to discuss about configuring the Scripting Modules. We need to follow the steps written below to configure scripting module −
Step 1
Step 1
从 Mule Palette 中搜索脚本模块,然后将脚本模块的 EXECUTE 操作拖动到您的流程中,如上所示。
Search for the Scripting module from Mule Palette and drag the EXECUTE operation of the scripting module into your flow as shown above.
Step 2
Step 2
现在,通过双击打开 Execute 配置选项卡。
Now, open the Execute configuration tab by double clicking on the same.
Step 3
Step 3
在 General 选项卡下,我们需要在 Code text window 中提供代码,如下所示: −
Under the General tab, we need to provide the code in the Code text window as shown below −
Step 4
Step 4
最后,我们需要从执行组件中选择 Engine 。以下是引擎列表: −
At last, we need to choose the Engine from the execute component. The list of engines is as below −
-
Groovy
-
Nashorn(javaScript)
-
jython(Python)
-
jRuby(Ruby)
配置 XML 编辑器中上述执行示例的 XML 如下: −
The XML of the above execution example in the Configuration XML editor is as follows −
<scripting:execute engine="jython" doc:name = "Script">
<scripting:code>
def factorial(n):
if n == 0: return 1
return n * factorial(n-1)
result = factorial(10)
</scripting:code>
</scripting:execute>
Message Sources
Mule 4 采用简化的 Mule 3 消息模型,使其在连接器中以一致的方式处理数据变得更加容易,而不会覆盖信息。在 Mule 4 消息模型中,每个 Mule 事件包含两部分内容: a message and variables associated with it 。
Mule 4 has a simplified model than Mule 3 message making it easier to work with data in a consistent way across connectors without overwriting information. In Mule 4 message model, each Mule event consists of two things: a message and variables associated with it.
Mule 消息包含有效负载及其属性,其中属性主要是元数据,例如文件大小。
A Mule message is having payload and its attributes, where attribute is mainly metadata such as file size.
变量保存任意用户信息,例如操作结果、辅助值等。
And a variable holds the arbitrary user information such as operation result, auxiliary values, etc.
Inbound
Mule 3 中的入站属性现在成为 Mule 4 中的属性。众所周知,入站属性存储通过消息源获得的有关有效负载的附加信息,但在 Mule 4 中,这是借助属性完成的。属性具有以下优点: −
The inbound properties in Mule 3 now becomes Attributes in Mule 4. As we know that inbound properties store additional information about the payload obtained through a message source, but this is now, in Mule 4, done with the help of attributes. Attributes have the following advantages −
-
With the help of attributes, we can easily see which data is available, because attributes are strongly typed.
-
We can easily access information contained in attributes.
以下是 Mule 4 中典型消息的示例: −
Following is the example of a typical message in Mule 4 −
Outbound
为了发送附加数据,必须由 Mule 连接器和传输中明确指定 Mule 3 中的出站属性。但在 Mule 4 中,可以使用 DataWeave 表达式为每个属性分别设置这些属性。它不会在主流程中产生任何副作用。
The outbound properties in Mule 3 must be explicitly specified by Mule connectors and transports in order to send additional data. But in Mule 4, each of those can be set separately, using a DataWeave expression for each one of them. It does not produce any side effect in the main flow.
例如,以下 DataWeave 表达式将执行 HTTP 请求并生成标头和查询参数,而无需设置消息属性。这在下面的代码中显示: −
For example, below DataWeave expression will perform a HTTP request and generates headers and query parameters without a need to set message properties. This is shown in the below code −
<http:request path = "M_issue" config-ref="http" method = "GET">
<http:headers>#[{'path':'input/issues-list.json'}]</http:headers>
<http:query-params>#[{'provider':'memory-provider'}]</http:query-params>
</http:request>
Message Processor
一旦 Mule 从消息源接收消息,消息处理器的任务就开始了。Mule 使用一个或多个消息处理器通过流处理消息。消息处理器的主要任务是在消息通过 Mule 流时对其进行转换、筛选、丰富和处理。
Once Mule receives a message from a message source, the work of message processor starts. The Mule uses one or more message processors to process the message through a flow. The main task of message processor is to transform, filter, enrich and process the message as it passes through the Mule flow.
Categorization of Mule Processor
以下是基于功能划分的 Mule 处理器类别: −
Following are the categories of Mule Processor, based on functions −
-
Connectors − These message processors send and receive data. They also plug data into external data sources via standard protocols or third-party APIs.
-
Components − These message processors are flexible in nature and perform business logic implemented in various languages like Java, JavaScript, Groovy, Python or Ruby.
-
Filters − They filter the messages and allow only specific messages to continue to be processed in a flow, based on specific criteria.
-
Routers − This message processor is used to control the flow of message to route, resequencing or split.
-
Scopes − hey basically wrap snippets of code for the purpose of defining fine-grained behavior within a flow.
-
Transformers − The role of transformers is to convert message payload type and data format to facilitate communication between systems.
-
Business Events − They basically capture data associated with key performance indicators.
-
Exception strategies − These message processors handle errors of any type that occur during message processing.
MuleSoft - Core Components & Configuration
Mule 最重要的能力之一是它可以使用组件执行路由、转换和处理,因此组合各种元素的 Mule 应用程序配置文件非常大。
One of the most important abilities of Mule is that it can perform routing, transforming, and processing with the components, because of which the configuration file of Mule application that combines various elements is very large in size.
Mule 提供的配置模式类型如下:
Following are the types of configuration patterns provided by Mule −
-
Simple service pattern
-
Bridge
-
Validator
-
HTTP proxy
-
WS proxy
Configuring the component
在 Anypoint 工作室中,我们可以按照以下步骤配置组件:
In Anypoint studio, we can follow the below steps to configure a component −
Step 1
Step 1
我们需要将希望在 Mule 应用程序中使用的组件拖动过来。例如,在此处,我们将 HTTP 侦听器组件用作如下所示:
We need to drag the component we wish to use in our Mule application. For example, here we use HTTP listener component as follows −
Step 2
Step 2
接下来,双击该组件以获取配置窗口。对于 HTTP 侦听器,如下所示:
Next, double click on the component to get the configuration window. For HTTP listener, it is shown below −
Step 3
Step 3
我们可以根据项目的需要配置组件。例如,我们针对 HTTP 侦听器组件所执行的操作:
We can configure the component as per the requirement of our project. Say for example, we did for HTTP listener component −
核心组件是 Mule 应用程序中工作流程的一个重要组成部分。处理 Mule 事件的逻辑由这些核心组件提供。在 Anypoint 工作室中,要访问这些核心组件,可以从 Mule 调色板中单击“核心”,如下所示:
Core components are one of the important building blocks of work flow in the Mule app. The logic for processing a Mule event is provided by these core components. In Anypoint studio, to access these core components, you can click on the Core from Mule Palette as shown below −
以下是各种 core components and their working in Mule 4 :
Following are various core components and their working in Mule 4 −
Custom Business Events
此核心组件用于收集有关 Mule 应用程序中处理业务交易的流以及消息处理程序的信息。换句话说,我们可以使用 Custom Business Event 组件在我们的工作流中添加以下内容:
This core component is used for the collection of information about flows as well as message processors that handle the business transactions in Mule app. In other words, we can use Custom Business Event component to add the following in our working flow −
-
Metadata
-
Key performance Indicators (KPIs)
How to add KPIs?
以下是为 Mule 应用程序中的流程添加关键绩效指标的步骤:
Following are the steps to add KPIs in our flow in Mule app −
Step 1 - 按照 Mule Palette → Core → Components → Custom Business Event 添加 Custom Business Event 组件到 Mule 应用程序中的工作流中。
Step 1 − Follow Mule Palette → Core → Components → Custom Business Event, to add Custom Business Event component to a working flow in your Mule app.
Step 2 - 单击组件以将其打开。
Step 2 − Click on the component to open it.
Step 3 - 现在,我们需要为显示名称和事件名称提供值。
Step 3 − Now, we need to provide values for Display Name and Event Name.
Step 4 - 要从消息有效负载中捕获信息,请添加关键绩效指标,如下所示:
Step 4 − To capture information from the message payload, add KPIs as follows −
-
Give a name (key) for the KPI (tracking: meta-data element) and a value. The name will be used in search interface of Runtime Manager.
-
Give a value that may be any Mule expression.
Dynamic Evaluate
此核心组件用于在 Mule 应用程序中动态选择脚本。我们还可以通过转换消息组件使用硬核脚本,但使用 Dynamic Evaluate 组件是一个更好的方法。此核心组件的工作方式如下 −
This core component is used for dynamically selecting a script in Mule app. We can also use hardcore script through the Transform Message Component but using Dynamic Evaluate component is a better way. This core component works as follows −
-
Firstly, it evaluates an expression that should result in another script.
-
Then it evaluates that script for the final result.
通过这种方式,它允许我们动态选择脚本,而不是对其进行硬编码。
In this way, it allows us to dynamically select the script rather than hardcoding it.
Example
以下是一个通过 ID 查询参数从数据库中选择脚本并将其存储在名为 MyScript 的变量中的示例。现在,动态评估组件将访问变量以调用脚本,以便它可以从 UName 查询参数中添加一个 name 变量。
Following is an example of selecting a script from database through an Id query parameter and storing that script in a variable named MyScript. Now, the dynamic-evaluate component will access the variable to invoke the scripts so that it can add a name variable from UName query parameter.
流程的 XML 配置如下所示 −
The XML configuration of the flow is given below −
<flow name = "DynamicE-example-flow">
<http:listener config-ref = "HTTP_Listener_Configuration" path = "/"/>
<db:select config-ref = "dbConfig" target = "myScript">
<db:sql>#["SELECT script FROM SCRIPTS WHERE ID =
$(attributes.queryParams.Id)"]
</db:sql>
</db:select>
<ee:dynamic-evaluate expression = "#[vars.myScript]">
<ee:parameters>#[{name: attributes.queryParams.UName}]</ee:parameters>
</ee:dynamic-evaluate>
</flow>
脚本可以使用消息、负载、变量或属性之类的上下文变量。但是,如果你想要添加自定义上下文变量,你需要提供一组键值对。
The script can use context variables like message, payload, vars or attributes. However, if you want to add custom context variable, you need to provide a set of key-value pairs.
Configuring Dynamic Evaluate
以下表格提供了配置 Dynamic Evaluate 组件的方法 −
Following table provides a way to configure Dynamic Evaluate component −
Field |
Value |
Description |
Example |
Expression |
DataWeave expression |
It specifies the expression to be evaluated into the final script. |
expression="#[vars.generateOrderScript]" |
Parameters |
DataWeave expression |
It specifies key-value pairs. |
#[{joiner: ' and ', id: payload.user.id}] |
Flow Reference Component
如果你想要在同一 Mule 应用程序中将 Mule 事件路由到另一个流或子流,那么流引用组件是正确的选择。
If you want to route the Mule event to another flow or sub-flow and back within the same Mule app, then flow reference component is the right option.
Characteristics
以下是此核心组件的特征 −
Following are the characteristics of this core component −
-
This core component allows us to treat the whole referenced flow like a single component in the current flow.
-
It breaks the Mule application into discrete and reusable units. For example, a flow is listing files on regular basis. It might reference another flow that processes the output of the list operation.
-
In this way, rather than appending the whole processing steps, we can append Flow References that points to the processing flow. The screenshot below shows that the Flow Reference Core Component is pointing towards a sub-flow named ProcessFiles.
Working
通过以下图表可以了解流引用组件的工作原理 −
The working of Flow Ref component can be understood with the help of following diagram −
该图表显示当一个流引用同一个应用程序中的另一个流时,Mule 应用程序中的处理顺序。当 Mule 应用程序中的主工作流被触发时,Mule 事件会一直传递并执行流,直到 Mule 事件到达流引用。
The diagram shows the processing order in Mule application when one flow references another flow in the same application. When the main working flow in Mule application triggered, the Mule event travels all through and executes the flow until the Mule event reaches Flow Reference.
在到达流引用后,Mule 事件从头到尾执行引用流。一旦 Mule 事件完成执行引用流,它将返回到主流。
After reaching Flow Reference, the Mule event executes the referenced flow from beginning to end. Once Mule event finishes executing the Ref Flow, it returns to the main flow.
Example
为了更好地理解, let us use this component in Anypoint Studio 。在此示例中,我们将 HTTP 侦听器用于 GET 消息,正如我们在上一章节中所做的一样。因此,我们可以拖放组件并进行配置。但对于此示例,我们需要添加子流组件并在其下方设置有效负载组件,如下所示 −
For better understanding, let us use this component in Anypoint Studio. In this example, we are taking HTTP listener to GET a message, as we did in the previous chapter. So, we can drag and drop the component and configure. But for this example, we need to add a Sub-flow component and set Payload component under that, as shown below −
接下来,我们需要通过双击配置 Set Payload 。此处我们给出的值“子流已执行”,如下所示 −
Next, we need to configure Set Payload, by double clicking on it. Here we are giving the value, “Sub flow executed” as shown below −
在成功配置子流组件后,我们需要将流引用组件设置在主流中设置有效负载之后,该组件可从 Mule Palette 中拖放,如下所示 −
Once successfully configuring the sub-flow component, we need the Flow Reference Component to set after Set Payload of main flow, which we can drag and drop from the Mule Palette as shown below −
接下来,在配置流引用组件时,我们需要在通用选项卡下选择流名称,如下所示 −
Next, while configuring the Flow Reference Component, we need to choose Flow Name under Generic tab as shown below −
现在,保存并运行此应用程序。要对此进行测试,请转至 POSTMAN,在 URL 栏中键入 http:/localhost:8181/FirstAPP ,然后您将收到消息“子流已执行”。
Now, save and run this application. To test this, go to POSTMAN and type http:/localhost:8181/FirstAPP in the URL bar, and you will get the message, Sub flow executed.
Logger Component
名为记录器的核心组件通过记录重要信息来帮助我们监控和调试 Mule 应用程序,例如错误消息、状态通知、有效负载等。在 AnyPoint 工作室中,它们出现在 Console 中。
The core component called logger helps us to monitor and debug our Mule application by logging important information like error messages, status notifications, payloads, etc. In AnyPoint studio, they appear in the Console.
Advantages
以下是记录器组件的一些优点:
Following are some advantages of Logger Component −
-
We can add this core component anywhere in the working flow.
-
We can configure it to log a string specified by us.
-
We can configure it to the output of a DataWeave expression written by us.
-
We can also configure it to any combination of strings and expressions.
Example
以下示例在浏览器中 Set Payload 中显示消息“Hello World”,并同时记录消息。
The example below displays the message “Hello World” in the Set Payload in a browser and logging the message also.
以下是上述示例中的流的 XML 配置 −
Following is the XML configuration of the flow in the above example −
<http:listener-config name = "HTTP_Listener_Configuration" host = "localhost" port = "8081"/>
<flow name = "mymuleprojectFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/"/>
<set-payload value="Hello World"/>
<logger message = "#[payload]" level = "INFO"/>
</flow>
Transfer Message Component
转换消息组件(也称为传输组件)允许我们将输入数据转换为新的输出格式。
Transform Message Component, also called Transfer component allows us to convert the input data into a new output format.
Methods to build Transformation
我们可以借助以下两个方法构建转换 −
We can build our transformation with the help of the following two methods −
Drag-and-Drop Editor (Graphical View) − 这是构建转换的第一种且是最常用的方法。在此方法中,我们可以使用此组件的可视化映射器来拖放传入数据结构的元素。例如,在以下示意图中,两个树视图显示了输入和输出的预期元数据结构。连接输入到输出字段的线表示两个树视图之间的映射。
Drag-and-Drop Editor (Graphical View) − This is the first and most used method to build our transformation. In this method, we can use this component’s visual mapper to drag-and-drop the elements of the incoming data structure. For example, in the following diagram, two tree views show the expected metadata structures of the input and output. Lines that connect input to output field represents the mapping between two tree views.
Script View − 转换的可视化映射也可在 DataWeave(用于 Mule 代码的语言)的帮助下表示。我们可以对高级转换(例如聚合、规范化、分组、连接、分区、旋转和筛选)进行编码。示例如下 −
Script View − The visual mapping of Transformation can also be represented with the help of DataWeave, a language for Mule code. We can do coding for some advanced transformations like aggregation, normalization, grouping, joining, partitioning, pivoting and filtering. The example is given below −
此核心组件主要接受变量、属性或消息有效负载的输入和输出元数据。我们可以为以下内容提供特定于格式的资源 −
This core component basically accepts input and output metadata for a variable, an attribute or message payload. We can provide format-specific resources for the following −
-
CSV
-
Schema
-
Flat file Schema
-
JSON
-
Object class
-
Simple Type
-
XML Schema
-
Excel Column name and type
-
Fixed Width Column name and type
MuleSoft - Endpoints
端点基本上包括那些在 Mule 应用程序的工作流中触发或启动处理的组件。它们在 Anypoint Studio 中称为 Source ,在 Mule 设计中心中称为 Triggers 。Mule 4 中的一个重要端点是 Scheduler component 。
Endpoints basically include those components that trigger or initiate the processing in a working flow of Mule application. They are called Source in Anypoint Studio and Triggers in the Design Center of Mule. One important endpoint in Mule 4 is Scheduler component.
Scheduler Endpoint
此组件基于时间条件工作,这意味着它使我们能够在基于时间条件满足时触发流。例如,调度程序可以触发事件以每隔 10 秒启动 Mule 工作流。我们还可以使用灵活的 Cron 表达式来触发调度程序端点。
This component works on time-based conditions, which means, it enables us to trigger a flow whenever a time-based condition is met. For example, a scheduler can trigger an event to start a Mule working flow every, say 10 seconds. We can also use flexible Cron expression to trigger a Scheduler Endpoint.
Important points about Scheduler
在使用调度程序事件时,我们需要考虑以下一些重要事项:
While using Scheduler event, we need to take care of some important points as given below −
-
Scheduler Endpoint follows the time-zone of the machine where Mule runtime is running.
-
Suppose if a Mule application is running in CloudHub, the Scheduler will follow the time-zone of the region in which the CloudHub worker is running.
-
At any given time, only one flow triggered by the Scheduler Endpoint can be active.
-
In Mule runtime cluster, the Scheduler Endpoint runs or triggers only on primary node.
Ways to configure a Scheduler
如上所述,我们可以配置调度程序端点以在固定时间间隔触发,或者我们还可以提供 Cron 表达式。
As discussed above, we can configure a scheduler endpoint to be triggered at a fixed interval or we can also give a Cron expression.
Parameters to configure a Scheduler (For Fixed Interval)
以下是要在常规时间间隔触发流的调度程序的参数:
Following are the parameters to set a scheduler to trigger a flow at regular intervals −
Frequency - 它基本上描述了调度程序端点将触发 Mule 流的频率。可以从时间单位字段中为其选择时间单位。如果您不为此提供任何值,它将使用 1000 的默认值。另一方面,如果您提供 0 或负值,它也将使用默认值。
Frequency − It basically describes at which frequency the Scheduler Endpoint will trigger the Mule flow. Unit of time for this can be selected from the Time Unit field. In case you do not provide any values for this, it will use the default value which is 1000. On the other side, if you provide 0 or a negative value, then also it uses the default value.
Start Delay - 这是应用程序启动后第一次触发 Mule 流之前我们必须等待的时间量。启动延迟的值以与频率相同的时间单位表示。它的默认值为 0。
Start Delay − It is the amount of time we must wait before triggering the Mule flow for the first time once the application is started. The value of Start delay is expressed in the same unit of time as the frequency. Its default value is 0.
Time Unit - 它描述了频率和启动延迟的时间单位。时间单位的可能值是毫秒、秒、分钟、小时、天。默认值为毫秒。
Time Unit − It describes the time unit for both Frequency and Start Delay. The possible values of time unit are Milliseconds, Seconds, Minute, Hours, Days. The default value is Milliseconds.
Parameters to configure a Scheduler (For Cron Expression)
实际上,Cron 是用于描述时间和日期信息的标准。如果您使用灵活的 Cron 表达式来使调度触发器触发,则调度程序端点将跟踪每秒,并在 Quartz Cron 表达式与时间日期设置相匹配时创建一个 Mule 事件。使用 Cron 表达式,可以一次触发事件或在常规时间间隔触发。
Actually, Cron is a standard used for describing time and date information. In case you use the flexible Cron expression to make Scheduler trigger, the Scheduler Endpoint keeps track of every second and creates a Mule event whenever the Quartz Cron expression matches the time-date setting. With Cron expression, the event can be triggered just once or at regular intervals.
下表给出了六个必填设置的日期时间表达式:
Following table gives the date-time expression of six required settings −
Attribute |
Value |
Seconds |
0-59 |
Minutes |
0-59 |
Hours |
0-23 |
Day of month |
1-31 |
Month |
1-12 or JAN-DEC |
Day of the week |
1-7 or SUN-SAT |
以下是一些由调度程序端点支持的 Quartz Cron 表达式的示例:
Some examples of Quartz Cron expressions supported by the Scheduler Endpoint are given below −
-
½ * * * * ? − means that the scheduler runs every 2 seconds of the day, every day.
-
0 0/5 16 * ?* − means that the scheduler runs every 5 minutes starting at 4 pm and ending at 4:55 pm, every day.
-
1 1 1 1, 5 * ? − means that the scheduler runs the first day of January and the first day of April, every year.
Example
以下代码每秒钟记录一次消息“hi”−
The following code logs the message “hi” every second −
<flow name = "cronFlow" doc:id = "ae257a5d-6b4f-4006-80c8-e7c76d2f67a0">
<doc:name = "Scheduler" doc:id = "e7b6scheduler8ccb-c6d8-4567-87af-aa7904a50359">
<scheduling-strategy>
<cron expression = "* * * * * ?" timeZone = "America/Los_Angeles"/>
</scheduling-strategy>
</scheduler>
<logger level = "INFO" doc:name = "Logger"
doc:id = "e2626dbb-54a9-4791-8ffa-b7c9a23e88a1" message = '"hi"'/>
</flow>
MuleSoft - Flow Control and Transformers
Flow Control (Routers)
流程控制组件的主要任务是接收输入的 Mule 事件,并将它路由到一个或多个独立的组件序列。它基本上是将输入的 Mule 事件路由到其他组件序列。因此,它也被称为路由器。选择和分散-收集路由器是流程控制组件中最常用的路由器。
The main task of Flow Control component is to take the input Mule event and route it to one or more separate sequences of components. It is basically routing the input Mule event to other sequence(s) of components. Therefore, it is also called as Routers. Choice and Scatter-Gather routers are the most used routers under Flow Control component.
Choice Router
顾名思义,此路由器应用 DataWeave 逻辑,从两个或更多个路由中选择一个。如前文所述,每个路由是一个独立的 Mule 事件处理器序列。我们可以将选择路由器定义为动态地通过流程路由消息的路由器,根据一组 DataWeave 表达式评估消息内容。
As the name suggests, this router applies DataWeave logic to choose one of two or more routes. As discussed earlier, each route is a separate sequence of Mule event processors. We can define choice routers as the router that dynamically routes message through a flow according to a set of DataWeave expressions used to evaluate message content.
Schematic diagram of Choice Router
使用选择路由器的效果就像向流程或大多数编程语言中的 if/then/else 代码块添加条件处理。以下是包含三个选项的选择路由器的原理图。其中,一个是默认路由器。
The effect of using Choice router is just like adding conditional processing to a flow or an if/then/else code block in most of the programming languages. Following is the schematic diagram of a Choice Router, having three options. Among those, one is the default router.
Scatter-Gather Router
另一种最常用的路由事件处理器是 Scatter-Gather component 。顾名思义,它基于分散(复制)和收集(合并)的基本原理工作。我们可以借助以下两点了解它的工作原理−
Another most used routing event processor is Scatter-Gather component. As its name implies, it works on the fundamentals of scatters (copy) and Gather (Consolidates). We can understand its working with the help of following two points −
-
First, this router copies (Scatter) a Mule event to two or more parallel routes. The condition is that each route must be a sequence of one or more event processors which is like a sub-flow. Each route in this case will create a Mule event by using a separate thread. Every Mule event will have its own payload, attributes as well as variables.
-
Next, this router gathers the created Mule events from each route and then consolidates them together into a new Mule event. After this, it passes this consolidated Mule event to the next event processor. Here the condition is that the S-G router will pass a consolidated Mule event to the next event processor only when every route is completed successfully.
Schematic Diagram of Scatter-Gather Router
以下是包含四个事件处理器的分散-收集路由器的原理图。它并行执行每个路由,而不是按顺序执行。
Following is the schematic diagram of a Scatter-Gather Router having four event processors. It executes every route in parallel and not sequentially.
Error Handling by Scatter-Gather Router
首先,我们必须了解在分散-收集组件内可能产生的错误类型。任何错误都可能在事件处理器中生成,导致分散-收集组件引发类型为 Mule: COMPOSITE_ERROR 的错误。仅在每个路由失败或完成之后,S-G 组件才会引发此错误。
First, we must have knowledge on the kind of error that can be generated within Scatter-Gather component. Any error might be generated within event processors leading the Scatter-Gather component to throw an error of type Mule: COMPOSITE_ERROR. This error will be thrown by the S-G component only after every route either fails or completes.
为了处理此错误类型,可以在分散-收集组件的每个路由中使用 try scope 。如果 try scope 成功处理错误,那么该路由肯定能够生成 Mule 事件。
To handle this error type, a try scope can be used in each route of Scatter-Gather component. If the error is successfully handled by try scope, then the route will be able to generate a Mule event, for sure.
Transformers
假设我们想要设置或删除任何 Mule 事件的一部分,那么 Transformer 组件是最佳选择。Transformer 组件的类型如下−
Suppose if we want to set or remove a part of any Mule event, Transformer component is the best choice. Transformer components are of the following types −
Remove variable transformer
正如其名称所述,此组件采用变量名,并从此 Mule 事件中删除此变量。
As the name implies, this component takes a variable name and removes that variable from the Mule event.
Configuring removing variable transformer
下表显示了在配置删除变量转换器时要考虑的字段名称及其描述:
The table below shows the name of fields and their description to be considered while configuring removing variable transformer −
Sr.No |
Field & Explanation |
1 |
Display Name (doc:name) We can customize this to display a unique name for this component in our Mule working flow. |
2 |
Name (variableName) It represents the name of the variable to remove. |
Set payload transformer
借助 set-payload 组件,我们可以更新消息的有效载荷,该有效载荷可以是文字字符串或 DataWeave 表达式。不建议针对复杂表达式或转换使用此组件。它可用于 selections 等简单表达式。
With the help of set-payload component, we can update the payload, which can be a literal string or DataWeave expression, of the message. It is not recommended to use this component for complex expressions or transformations. It can be used for simple ones like selections.
下表显示了在配置设置有效载荷转换器时要考虑的字段名称及其描述:
The table below shows the name of fields and their description to be considered while configuring set payload transformer −
Field |
Usage |
Explanation |
Value (value) |
Mandatory |
The value filed is required for setting a payload. It will accept a literal string or DataWeave expression defining how to set the payload. The examples are like “some string” |
Mime Type (mimeType) |
Optional |
It’s optional but represents the mime type of the value assigned to the payload of message. The examples are like text/plain. |
Encoding (encoding) |
Optional |
It’s also optional but represents the encoding of the value that is assigned to the payload of message. The examples are like UTF-8. |
我们可以通过 XML 配置代码设置有效负载 -
We can set a payload through XML configuration code −
With Static Content - 以下 XML 配置代码将使用静态内容设置有效负载 -
With Static Content − Following XML configuration code will set the payload by using static content −
<set-payload value = "{ 'name' : 'Gaurav', 'Id' : '2510' }"
mimeType = "application/json" encoding = "UTF-8"/>
With Expression Content - 以下 XML 配置代码将使用表达式内容设置有效负载 -
With Expression Content − Following XML configuration code will set the payload by using Expression content −
<set-payload value = "#['Hi' ++ ' Today is ' ++ now()]"/>
以上示例将把今天的日期追加到消息有效负载“Hi”中。
The above example will append today’s date with the message payload “Hi”.
Set Variable Transformer
借助 set variable 组件,我们可以创建或更新变量以存储值,这些值可以是简单的文字值(例如字符串、消息有效负载或属性对象),以便在 Mule 应用程序的流程中使用。不建议将此组件用于复杂表达式或转换。它可以用于简单的表达式,如 selections 。
With the help of set variable component, we can create or update a variable to store values which can be simple literal values like strings, message payloads or attribute objects, for use within the flow of Mule application. It is not recommended to use this component for complex expressions or transformations. It can be used for simple ones like selections.
Configuring set variable transformer
下表显示了在配置设置有效载荷转换器时要考虑的字段名称及其描述:
The table below shows the name of fields and their description to be considered while configuring set payload transformer −
Field |
Usage |
Explanation |
Variable Name (variableName) |
Mandatory |
It is required filed and it represents the name of the variable. While giving the name, follow the naming convention like it must contain number, characters and underscores. |
Value (value) |
Mandatory |
The value filed is required for setting a variable. It will accept a literal string or DataWeave expression. |
Mime Type (mimeType) |
Optional |
It’s optional but represents the mime type of the variable. The examples are like text/plain. |
Encoding (encoding) |
Optional |
It’s also optional but represents the encoding of the variable. The examples are like ISO 10646/Unicode(UTF-8). |
Example
以下示例将变量设置为消息有效负载 -
The example below will set the variable to the message payload −
Variable Name = msg_var
Value = payload in Design center and #[payload] in Anypoint Studio
类似地,以下示例将变量设置为消息有效负载 -
Similarly, the example below will set the variable to the message payload −
Variable Name = msg_var
Value = attributes in Design center and #[attributes] in Anypoint Studio.
MuleSoft - Web Services Using Anypoint Studio
REST Web Service
REST 的全称是表述性状态转移,它与 HTTP 绑定。因此,如果您想设计一个专门在网络上使用的应用程序,REST 是最佳选择。
The full form of REST is Representational State Transfer which is bound with HTTP. Hence, if you want to design an application to be used exclusively on the web, REST is the best option.
Consuming RESTful Web Services
在以下示例中,我们将使用 REST 组件和 Mule Soft 提供的名为 American Flights details 的一个公共 RESTful 服务。它有各种详细信息,但我们将使用 GET: http://training-american-ws.cloudhub.io/api/flights 来返回所有航班详细信息。如前所述,REST 与 HTTP 绑定,因此我们也需要两个 HTTP 组件——一个侦听器和一个请求,用于此应用程序。以下屏幕截图显示了 HTTP 侦听器的配置 -
In the following example, we will be using REST component and one public RESTful service provided by Mule Soft called American Flights details. It has various details but we are going to use GET:http://training-american-ws.cloudhub.io/api/flights that will return all flight details. As discussed earlier, REST is bound with HTTP, hence we need two HTTP components ― one is Listener and other is Request, for this application too. Below screenshot shows the configuration for HTTP listener −
Configuring and passing arguments
HTTP 请求的配置如下 -
The configuration for HTTP request is given below −
现在,根据我们的工作空间流程,我们采用了记录器,因此可以按如下方式对其进行配置 -
Now, as per our workspace flow, we have taken logger so it can be configured as below −
在消息选项卡中,我们编写代码将有效负载转换为字符串。
In the message tab, we write code to convert the payload into strings.
Testing the Application
现在,保存并运行该应用程序,然后转到 POSTMAN 中以检查最终输出,如下所示 -
Now, save and run the application and go to POSTMAN to check the final output as shown below −
您可以看到它通过使用 REST 组件给出了航班详细信息。
You can see it gives the flight details by using REST component.
SOAP Component
SOAP 的全称为 Simple Object Access Protocol 。它基本上是用于在 Web 服务实施中交换信息的通信协议规范。接下来,我们将在 Anypoint Studio 中使用 SOAP API 来使用 Web 服务访问信息。
The full form of SOAP is Simple Object Access Protocol. It is basically a messaging protocol specification for exchanging information in the implementation of web services. Next, we are going to use SOAP API in Anypoint Studio to access the information using web services.
Consuming SOAP-based Web Services
对于此示例,我们将使用名为国家/地区信息服务的公共 SOAP 服务,该服务保留与国家/地区信息相关的服务。其 WSDL 地址为: http://www.oorsprong.org/websamples.countryinfo/countryinfoservice.wso?WSDL
For this example, we are going to use public SOAP service whose name is Country Info Service which retains the services related to country information. Its WSDL address is: http://www.oorsprong.org/websamples.countryinfo/countryinfoservice.wso?WSDL
首先,我们需要从 Mule Palette 的画布中拖动 SOAP 消费,如下所示:
First, we need to drag SOAP consume in our canvas from Mule Palette as shown below −
Configuring and Passing Arguments
接下来,我们需要配置 HTTP 请求,如下面所示,如上一个示例中所做:
Next, we need to configure HTTP request as done in above example as given below −
现在,我们还需要配置 Web 服务使用者,如下所示:
Now, we also need to configure the Web Service Consumer as shown below −
在 WSDL 位置的地方,我们需要提供 WSDL 的 Web 地址,如上所述(此示例)。提供 Web 地址后,Studio 会自行搜索服务、端口和地址。您无需手动提供它。
At the place of WSDL Location, we need to provide the web address of WSDL, which is provided above (for this example). Once you give the web address, Studio will search for service, Port and Address by itself. You need not provide it manually.
Testing the Application
保存并运行应用程序,然后转到 Google Chrome 检查最终输出。键入 http://localhist:8081/helloSOAP (此示例),它将显示如下面的屏幕截图所示的国家/地区名称(按代码):
Save and run the application and go to Google Chrome for checking the final output. Type http://localhist:8081/helloSOAP (for this example) and it will show the country name by code as shown in the screenshot below −
MuleSoft - Mule Error Handling
新的 Mule 错误处理是 Mule 4 中进行的最大、最重要的更改之一。新的错误处理可能看起来很复杂,但它更好、更高效。在本章中,我们将讨论 Mule 错误的组成部分、错误类型、Mule 错误类别和用于处理 Mule 错误的组件。
The new Mule error handling is one of the biggest and major changes done in Mule 4. The new error handing may seem complex, but it is better and more efficient. In this chapter, we are going to discuss about components of Mule error, Error types, categories of Mule error and components for handling Mule errors.
Components of Mule Error
Mule 错误是 Mule 异常失败造成的结果,包括以下组件:
Mule error is the result of Mule exception failure has the following components −
Description
它是 Mule 错误的一个重要组成部分,将提供有关问题的信息。其表达式如下:
It is an important component of Mule error which will give description about the problem. Its expression is as follows −
#[error.description]
Type
Mule 错误类型组件用于描述问题。它还允许在错误处理程序内进行路由。其表达式如下:
The Type component of Mule error is used to characterize the problem. It also allows routing within an error handler. Its expression is as follows −
#[error.errorType]
Cause
Mule 错误的 Cause 组件提供了导致错误的底层 Java 可抛出项。其表达式如下:
The Cause component of Mule error gives the underlying java throwable that causes the failure. Its expression is as follows −
#[error.cause]
Message
Mule 错误中的消息组件显示有关错误的可选消息。其表达式如下:
The Message component of Mule error shows an optional message regarding the error. Its expression is as follows −
#[error.errorMessage]
Child Errors
Mule 错误的子错误组件提供了内部错误的可选集合。这些内部错误主要由 Scatter-Gather 等元素用于提供聚合路由错误。其表达式如下:
The Child Errors component of Mule error gives an optional collection of inner errors. These inner errors are mainly used by elements like Scatter-Gather to provide aggregated route errors. Its expression is as follows −
#[error.childErrors]
Example
如果 HTTP 请求的状态代码为 401 失败,则 Mule 错误如下:
In case of failure of HTTP request with a 401 status code, the Mule Errors are as follows −
Description: HTTP GET on resource ‘http://localhost:8181/TestApp’
failed: unauthorized (401)
Type: HTTP:UNAUTHORIZED
Cause: a ResponseValidatorTypedException instance
Error Message: { "message" : "Could not authorize the user." }
Sr.NO |
Error Type and Description |
1 |
TRANSFORMATION This Error Type indicates an error occurred while transforming a value. The transformation is Mule Runtime internal transformation and not the DataWeave transformations. |
2 |
EXPRESSION This kind of Error Type indicates an error occurred while evaluating an expression. |
3 |
VALIDATION This kind of Error Type indicates a validation error occurred. |
4 |
DUPLICATE_MESSAGE A kind of validation error which occurs when a message being processed twice. |
5 |
REDELIVERY_EXHAUSTED This kind of Error Type occurs when maximum attempts to reprocess a message from a source has been exhausted. |
6 |
CONNECTIVITY This Error Type indicates a problem while establishing a connection. |
7 |
ROUTING This Error Type indicates an error occurred while routing a message. |
8 |
SECURITY This Error Type indicates a security error occurred. For example, invalid credentials received. |
9 |
STREAM_MAXIMUM_SIZE_EXCEEDED This Error Type occurs when the maximum size allowed for a stream exhausted. |
10 |
TIMEOUT It indicates the timeout while processing a message. |
11 |
UNKNOWN This Error Type indicates an unexpected error occurred. |
12 |
SOURCE It represents the occurrence of an error in the source of the flow. |
13 |
SOURCE_RESPONSE It represents the occurrence of an error in the source of the flow while processing a successful response. |
在上面的示例中,您可以看到 Mule 错误的消息组件。
In the above example, you can see the message component of mule error.
Error Types
让我们借助 Mule 错误类型的特性来理解错误类型 -
Let us understand the Error Types with the help of its characteristics −
-
The first characteristics of Mule Error Types is that it consists of both, a namespace and an identifier. This allows us to distinguish the types according to their domain. In the above example, the Error Type is HTTP: UNAUTHORIZED.
-
The second and important characteristic is that the Error Type may have a parent type. For example, the Error Type HTTP: UNAUTHORIZED has MULE:CLIENT_SECURITY as the parent which in turn also has a parent named MULE:SECURITY. This characteristic establishes the Error Type as specification of more global item.
Kinds of Error Types
所有错误分类如下 -
Following are the categories under which all the errors fall −
ANY
此类别下的错误是在流程中可能发生的错误。这些错误不太严重,可以轻松处理。
The errors under this category are the errors that may occur in a Flow. They are not so severe and can be handled easily.
CRITICAL
此类别下的错误是无法处理的严重错误。以下是此类别下的错误类型列表 -
The errors under this category are the severe errors that cannot be handled. Following is the list of Error Types under this category −
Sr.NO |
Error Type and Description |
1 |
OVERLOAD This Error Type indicates an error occurred due to problem of overloading. In this case, the execution will be rejected. |
2 |
FATAL_JVM_ERROR This kind of Error Type indicates the occurrence of a fatal error. For example, stack overflow. |
CUSTOM Error Type
自定义错误类型是由我们定义的错误。它们可以在映射或引发错误时定义。我们必须为这些错误类型提供一个特定的自定义命名空间,以便将它们与 Mule 应用程序中的其他现有错误类型区分开来。例如,在使用 HTTP 的 Mule 应用程序中,我们不能使用 HTTP 作为自定义错误类型。
The CUSTOM Error Types are the errors that are defined by us. They can be defined when mapping or when raising the errors. We must give a specific custom namespace to these Error Types for distinguishing them from the other existing Error Types within Mule application. For example, in Mule application using HTTP, we cannot use HTTP as the custom error type.
Categories of Mule Error
广义上讲,Mule 中的错误可以分为两类,即 Messaging Errors and System Errors 。
In broad sense, the errors in Mule can be divided into two categories namely, Messaging Errors and System Errors.
Messaging Error
这一类 Mule 错误与 Mule 流相关。每当 Mule 流中出现问题时,Mule 都会引发消息传递错误。我们可以在错误处理组件内设置 On Error 组件,以处理这些 Mule 错误。
This category of Mule error is related to the Mule flow. Whenever a problem occurs within a Mule flow, Mule throws a messaging error. We can set up On Error component inside the error handler component to handle these Mule errors.
System Error
系统错误表示系统级发生的异常。如果没有 Mule 事件,系统错误将由系统错误处理程序处理。系统错误处理程序处理的异常类型如下所示:
System error indicates an exception occurring at the system level. If there is no Mule event, the system error is handled by a system error handler. The following kind of exceptions handle by a system error handler −
-
Exception that occurs during an application start-up.
-
Exception that occurs when a connection to an external system fails.
如果发生系统错误,Mule 会将错误通知发送给已注册的监听器。它还会记录错误。另一方面,如果错误是由连接失败引起的,Mule 将执行重新连接策略。
In case a system error occurs, Mule sends an error notification to the registered listeners. It also logs the error. On the other hand, Mule executes a reconnection strategy if the error was caused by a connection failure.
Handling Mule Errors
Mule 具有以下两个错误处理程序来处理错误:
Mule has following two Error Handlers for handling the errors −
On-Error Error Handlers
第一个 Mule 错误处理程序是 On-Error 组件,该组件定义了它们可以处理的错误类型。如前所述,我们可以在 ERROR HANDLER 组件(类似范围)内配置 On-Error 组件。每个 Mule 流只包含一个错误处理程序,但该错误处理程序可以包含我们需要的任意多个 On-Error 范围。在流内借助 On-Error 组件处理 Mule 错误的步骤如下:
The first Mule error handler is On-Error component, that defines the types of errors they can handle. As discussed earlier, we can configure On-Error components inside the scope-like Error Handler component. Each Mule flow contain only one error handler, but this error handler can contain as many On-Error scope as we needed. The steps for handling the Mule error inside the flow, with the help of On-Error component, are as follows −
-
First, whenever a Mule flow raises an error, the normal flow execution stops.
-
Next, the process will be transferred to the Error Handler Component that already have On Error component to match the error types and expressions.
-
At last, the Error Handler component routes the error to the first On Error scope that matches the error.
以下是 Mule 支持的两种类型的 On-Error 组件:
Following are the two types of On-Error components supported by Mule −
On-Error Propagate
On-Error Propagate 组件执行,但会将错误传播到下一级并中断所有者的执行。如果它由 On Error Propagate 组件处理,事务将回滚。
On-Error Propagate component executes but propagates the error to the next level and breaks the owner’s execution. The transaction will be rolled back if it is handled by On Error Propagate component.
On-Error Continue
与 On-Error Propagate 组件类似,On-Error Continue 组件也会执行事务。唯一条件是,如果所有者已成功完成执行,则该组件将使用执行结果作为其所有者的结果。如果它由 On-Error Continue 组件处理,事务将提交。
Like On-Error Propagate component, On-Error Continue component also executes the transaction. The only condition is, if the owner had completed the execution successfully then this component will use the result of the execution as the result of its owner. The transaction will be committed if it is handled by On-Error Continue component.
Try Scope Component
Try Scope 是 Mule 4 中众多新功能之一。它的工作方式类似于 JAVA 中的 try 块,在其中我们通常将有异常可能性的代码封装起来,以便可以处理它而不会中断整个代码。
Try Scope is one of many new features available in Mule 4. It works similar to try block of JAVA in which we used to enclose the code having the possibility of being an exception, so that it can be handled without breaking the whole code.
我们可以在 Try Scope 中包装一个或多个 Mule 事件处理器,此后,try scope 将捕获并处理这些事件处理器引发的任何异常。try scope 的主要工作围绕其自己的错误处理策略进行,该策略支持对其内部组件进行错误处理,而不是整个流。因此,我们不需要将流提取到一个单独的流中。
We can wrap one or more Mule event processors in Try Scope and thereafter, try scope will catch and handle any exception thrown by these event processors. The main working of try scope revolves around its own error handling strategy which supports error handling on its inner component instead of whole flow. That is why we do not need to extract the flow into a separate flow.
Example
以下是 try scope 用法的一个示例:
Following is an example of the use of try scope −
Configuring try scope for handling transactions
众所周知,事务是一系列绝不应该部分执行的操作。在事务范围内执行的所有操作都在同一线程中执行,如果发生错误,它将导致回滚或提交。我们可以按以下方式配置 try scope,以便它将子操作视为一个事务。
As we know, a transaction is a series of actions that should never be executed partially. All the operations within the scope of a transaction are executed in the same thread and if an error occurs, it should lead to a rollback or a commit. We can configure the try scope, in the following manner, so that it treats child operations as a transaction.
-
INDIFFERENT [Default] − If we choose this configuration on try block, then the child actions will not be treated as a transaction. In this case, error causes neither rollback nor commits.
-
ALWAYS_BEGIN − It indicates that a new transaction will be started every time the scope is executed.
-
BEGIN_OR_JOIN − It indicates that if the current processing of the flow has already started a transaction, join it. Otherwise, start a new one.
MuleSoft - Mule Exception handling
对于每个项目,一个事实是肯定会发生例外。这就是捕获、分类和处理异常非常重要的原因,从而系统/应用程序不会处于不一致的状态。有一个默认异常策略,它隐式应用于所有 Mule 应用程序。自动回滚任何待处理事务是默认异常策略。
In case of every project, the fact about the exceptions is that they are bound to happen. That is why it is important to catch, categorize and handle exceptions so that the system/application is not left in an inconsistent state. There is a default exception strategy which is implicitly applied to all Mule applications. Rollback any pending transaction automatically is the default exception strategy.
Exceptions in Mule
在深入研究异常处理之前,我们应该了解会发生哪种异常以及开发人员在设计异常处理程序时必须具备的三个基本问题。
Before diving deep into exceptional handling, we should understand what kind of exceptions can occur along with three basic questions that a developer must have while designing exception handlers.
Which Transport is important?
在设计异常处理程序之前,此问题非常相关,因为并非所有传输都支持跨国性。
This question has ample relevance before designing exception handlers because all transports do not support transnationality.
File 或 HTTP 不支持事务。因此,如果在这些情况下发生异常,我们必须手动对其进行管理。
File or HTTP does not support transactions. That is why, if an exception occurs in these cases, we must manage it manually.
Databases 支持事务。在这种情况下设计异常处理程序时,我们必须记住数据库事务可以自动回滚(如果需要的话)。
Databases support transactions. While designing exception handlers in this case, we must keep in mind that database transactions can automatically rollback (if required).
对于 REST APIs ,我们应该记住它们应该返回正确的 HTTP 状态码。例如,资源未找到时为 404。
In case of REST APIs, we should keep in mind that they should return the correct HTTP status codes. For example, 404 for a resource not found.
Which Message Exchange Pattern to be used?
在设计异常处理程序时,我们必须注意消息交换模式。可以有同步(请求-响应)或异步(防火)消息模式。
While designing exception handlers, we must take care about Message exchange pattern. There can be synchronous (request-reply) or asynchronous (fire-forget) message pattern.
Synchronous message pattern 基于请求-响应格式,这意味着此模式将期待响应,并且在返回响应或超时之前将被阻塞。
Synchronous message pattern is based on request-reply format which means this pattern will expect a response and will be blocked until a response is returned or time out happens.
Asynchronous message pattern 基于防火格式,这意味着此模式假定最终将处理请求。
Asynchronous message pattern is based on fire-forget format which means this pattern assumes that the requests will ultimately be processed.
Which type of exception is it?
非常简单的规则是,你将根据异常的类型来处理该异常。了解这个异常是由系统/技术问题还是业务问题引起的非常重要?
Very simple rule is that you will handle the exception based on its type. It is very important to know whether the exception is caused by a system/technical issue or a business issue?
system/technical issue 发生的异常(例如网络中断)应该由重试机制自动处理。
An exception occurred by system/technical issue (such as network outage) should be automatically handled by a retry mechanism.
另一方面, by a business issue 发生的异常(例如无效数据)不应该通过应用重试机制来解决,因为在未修复根本原因的情况下,重试是没有用的。
On the other hand, an exception occurred by a business issue (such as invalid data) should not be solved by applying retry mechanism because it is not useful to retry without fixing the underlying cause.
Why to Categorize Exceptions?
众所周知,并非所有异常都是相同的,因此对异常进行分类非常重要。从高层面上讲,可以将异常分类为以下两种类型 −
As we know that all the exceptions are not same, it is very important to categorize the exceptions. At high level, the exceptions can be classified into the following two types −
Business Exceptions
业务异常发生的主要原因是错误的数据或不正确的流程流。此类异常通常本质上不可重试,因此配置 rollback 不好。即使应用 retry 机制也没有任何意义,因为在不修复根本原因的情况下,重试是没有用的。为了处理此类异常,应立即停止处理,并将异常作为对死信队列响应发送回。还应该向运维发送通知。
The main reasons for the occurrence of business exceptions are incorrect data or incorrect process flow. These kind of exceptions are typically non-retriable in nature and hence it is not good to configure a rollback. Even applying retry mechanism would not make any sense because it is not useful to retry without fixing the underlying cause. In order to handle such exceptions, the processing should stop immediately, and the exception sent back as a response to a dead letter queue. A notification should also send to the operations.
Non-business Exceptions
非业务异常发生的主要原因是系统问题或技术问题。这类异常本质上是可重试的,因此为了解决这些异常,最好配置 retry 机制。
The main reasons for the occurrence of non-business exceptions are system issue or technical issue. These kinds of exceptions are retriable in nature and hence it’s good to configure a retry mechanism in order to solve these exceptions.
Exception Handling Strategies
Mule 有以下五种异常处理策略 −
Mule has the following five exception handling strategies −
Default Exception Strategy
Mule 隐式地将此策略应用于 Mule 流程。它可以处理我们流程中的所有异常,但是也可以通过添加 catch、选择或回滚异常策略来覆盖它。此异常策略将回滚任何待定的事务并记录异常。此异常策略的一个重要特征是,如果没有事务,它还将记录异常。
Mule implicitly applies this strategy to the Mule flows. It can handle all the exceptions in our flow, but it can also be overridden by adding a catch, Choice or Rollback exception strategy. This exception strategy will roll back any pending transactions and logs the exceptions too. An important characteristic of this exception strategy is that it will also log the exception if there is no transaction.
作为默认策略,Mule 在流中出现任何错误时实现此策略。我们无法在 AnyPoint Studio 中进行配置。
As being the default strategy, Mule implements this when any error occurs in the flow. We cannot configure in AnyPoint studio.
Rollback Exception Strategy
假设如果没有可能纠正错误的解决方案,该怎么办?一种解决方案是使用回滚异常策略,该策略将回滚事务,同时向父流程的入站连接器发送消息以重新处理消息。当我们想要重新处理消息时,此策略也非常有用。
Suppose if there is no possible solution to correct the error then what to do? A solution is to use Rollback Exception Strategy which will roll back the transaction along with sending a message to the inbound connector of parent flow to reprocess the message. This strategy is also very useful when we want to reprocess a message.
Example
此策略可以应用于资金存入支票/储蓄账户的银行交易中。我们可以在此处配置回滚异常策略,因为如果在交易过程中发生错误,此策略会将消息回滚到流的开头,以重新尝试处理。
This strategy can be applied to banking transaction where funds are getting deposited in a checking/savings account. We can configure a rollback exception strategy here because in case if an error occurs during the transaction, this strategy rolls the message back to the beginning to the flow to reattempt processing.
Catch Exception Strategy
此策略捕获其父流程中引发的所有异常。它通过处理父流程引发的所有异常来覆盖 Mule 的默认异常策略。我们可以使用 catch 异常策略来避免将异常传播到入站连接器和父流程。
This strategy catches all the exceptions that are thrown within its parent flow. It overrides Mule’s default exception strategy by processing all the exceptions thrown by the parent flow. We can use a catch exception strategy to avoid propagating exceptions to inbound connectors and parent flows as well.
此策略还确保在发生异常时不会回滚流处理的事务。
This strategy also ensures that a transaction processed by the flow is not rolled back when an exception occurs.
Example
此策略可以应用于航班预订系统,其中我们有一个用于处理来自队列的消息的流程。消息丰富器在消息中添加了一个属性以分配座位,然后将消息发送到另一个队列。
This strategy can be applied to flight booking system in which we have a flow for processing messages from a queue. A message enricher adds a property on the message for assignment of seat and then sends the message to another queue.
现在,如果此流程中发生任何错误,则消息将引发异常。在这里,我们的 catch 异常策略可以添加一个带有适当消息的标头,并可以将该消息从流程推送到下一个队列。
Now if any error occurs in this flow, then the message will throw an exception. Here, our catch exception strategy can add a header with an appropriate message and can push that message out of the flow to the next queue.
Choice Exception Strategy
如果您想根据消息内容来处理异常,那么选择异常策略将是最佳选择。此异常策略的工作方式如下 −
In case you want to handle the exception based on the message content, then choice exception strategy would be the best choice. The working of this exception strategy will be as follows −
-
First, it catches all the exceptions thrown within the parent flow.
-
Next, it checks for the message content and exception type.
-
And at last, it routes the message to the appropriate exception strategy.
在选择异常策略中,会有多个异常策略,例如 Catch 或 Rollback。如果没有在此异常策略中定义任何策略,它会将消息路由到默认异常策略。它不会执行任何提交或回滚或消费活动。
There would be more than one exception strategy like Catch or Rollback, defined within choice exception strategy. In case there is no strategy defined under this exception strategy, then it will route the message to the default exception strategy. It never performs any commit or rollback or consume activities.
Reference Exception Strategy
这涉及一个在独立配置文件中定义的常见异常策略。如果消息引发异常,此异常策略会引用在全局 catch、rollback 或 choice 异常策略中定义的错误处理参数。与 choice 异常策略一样,它也不会执行任何 commit 或 rollback 或消费活动。
This refers to a common exception strategy that is defined in a separate configuration file. In case when a message throws an exception, this exception strategy will refer to the error handling parameters defined in a global catch, rollback or choice exception strategy. Like choice exception strategy, it never performs any commit or rollback or consume activities also.
MuleSoft - Testing with MUnit
我们了解,单元测试是一种通过该测试源代码的各个单元以确定它们是否适合使用的方法。Java 程序员可以使用 Junit 框架来编写测试用例。同样,MuleSoft 也拥有一个名为 MUnit 的框架,它允许我们为我们的 API 和集成编写自动化测试用例。它非常适合持续集成/部署环境。MUnit 框架的最大优势之一是我们可以将其与 Maven 和 Surefire 集成。
We understand unit testing is a method by which individual units of source code can be tested to determine whether they are fit for use or not. Java programmers can use Junit framework to write test cases. Similarly, MuleSoft is also having a framework called MUnit allowing us to write automated test cases for our APIs and integrations. It is a perfect fit for continuous integration/deployment environment. One of the biggest advantages of MUnit framework is that we can integrate it with Maven and Surefire.
Features of MUnit
以下是 Mule MUnit 测试框架的一些非常有用的功能
Following are some of the very useful features of Mule MUnit testing framework −
-
In MUnit framework, we can create our Mule test by using Mule code as well as Java code.
-
We can design and test our Mule apps and APIs, either graphically or in XML, within Anypoint Studio.
-
MUnit allows us to easily integrate the testing into existing CI/CD process.
-
It provides auto-generated tests and coverage reports; hence the manual work is minimal.
-
We can also use local DB/FTP/mail servers to make testing more portable through the CI process.
-
It allows us to enable or disable tests.
-
We can also extend the MUnit framework with plugins.
-
It allows us to verify message processor calls.
-
With the help of MUnit testing framework, we can disable endpoint connectors as well as flow inbound end points.
-
We can check error reports with Mule stack trace.
Latest Release of Mule MUnit Testing Framework
MUnit 2.1.4 是 Mule MUnit 测试框架的最新版本。它需要以下硬件和软件要求
MUnit 2.1.4 is the latest release of Mule MUnit testing framework. It requires following hardware and software requirements −
-
MS Windows 8+
-
Apple Mac OS X 10.10+
-
Linux
-
Java 8
-
Maven 3.3.3, 3.3.9, 3.5.4, 3.6.0
它与 Mule 4.1.4 和 Anypoint Studio 7.3.0 兼容。
It is compatible with Mule 4.1.4 and Anypoint Studio 7.3.0.
MUnit and Anypoint Studio
如上文所讨论的,MUnit 已完全集成在 Anypoint Studio 中,我们可以以图形方式或在 Anypoint Studio 内以 XML 形式设计和测试 Mule 应用程序和 API。换句话说,我们可以使用 Anypoint Studio 的图形界面执行以下操作 -
As discussed, MUnit is fully integrated in Anypoint studio and we can design and test our Mule apps and APIs graphically or in XML within Anypoint studio. In other words, we can use graphical interface of Anypoint Studio to do the following −
-
For creating and designing MUnit tests
-
For running our tests
-
For viewing test results as well as coverage report
-
For debugging the tests
因此,让我们开始逐一讨论每项任务。
So, let us start discussing each task one by one.
Creating and Designing MUnit Tests
一旦你启动新项目,它就会自动向我们的项目中添加一个新文件夹,即 src/test/munit 。例如,我们启动了一个名为 test_munit 的新 Mule 项目,你可以在下图中看到,它在我们的项目下添加了上述文件夹。
Once you start new project, it will automatically add a new folder namely src/test/munit to our project. For example, we started a new Mule project namely test_munit, you can see in the below image, it adds the above-mentioned folder under our project.
现在,一旦启动新项目,就有两种基本方法可以在 Anypoint Studio 中创建新的 MUnit 测试 -
Now, once you started new project, there are two basic ways to create a new MUnit test in Anypoint Studio −
-
By Right-Clicking the Flow − In this method, we need to right-click the specific flow and select MUnit from the drop-down menu.
-
By Using the Wizard − In this method, we need to use the wizard for creating a test. It allows us to create a test for any flow in the workspace.
我们将使用“右键单击流”的方式为特定流创建测试。
We are going to use ‘Right-click the flow’ way to create a test for specific flow.
首先,我们需要按如下方式在工作空间中创建一个流 -
First, we need to create a flow in the workspace as follows −
现在,右键单击此流并选择 MUnit 为此流创建测试,如下所示 -
Now, right click on this flow and select MUnit to create a test for this flow, as shown below −
它将创建一个以流所在的 XML 文件命名的新测试套件。在这种情况下, test_munit-test-suite 是新测试套件的名称,如下所示 -
It will create a new test suite named after the XML file where the flow resides. In this case, test_munit-test-suite is the name of the new test suite as shown below −
以下是用于上述消息流的 XML 编辑器 -
Following is the XML editor for the above message flow −
现在,我们可以通过从 Mule Palette 中拖动 MUnit 消息处理器将其添加到测试套件中。
Now, we can add an MUnit message processor to the test suite by dragging it from Mule Palette.
如果你想通过向导创建测试,请按照 File → New → MUnit 操作,它将引导你进入以下 MUnit 测试套件 -
If you want to create a test via the Wizard then follow File → New → MUnit and it will lead you to the following MUnit testing suite −
Configuring the test
在 Mule 4 中,我们有两个新部分,分别是 MUnit 和 MUnit Tools ,它们共同拥有所有 MUnit 消息处理器。你可以在你的 MUnit 测试区域中拖动任何消息处理器。在下图中所示 -
In Mule 4, we have two new sections namely MUnit and MUnit Tools, collectively having all MUnit message processor. You can drag any of the message processor in your MUnit test area. It is shown in the below screenshot −
现在,如果你想在 Anypoint Studio 中编辑你的套装或测试的配置,则需要按照以下步骤操作 −
Now, if you want to edit the configuration for your suit or test in Anypoint Studio, then you need to follow the below steps −
Step 1
Step 1
转到 Package Explorer 并右键单击你的套装或测试的 .xml file 。然后,选择 Properties 。
Go to the Package Explorer and right click on the .xml file for your suite or test. Then, select the Properties.
Step 2
Step 2
现在,在属性窗口中,我们需要单击 Run/Debug Setting*s. After this click *New 。
Now, in the Properties window, we need to click Run/Debug Setting*s. After this click *New.
Step 3
Step 3
最后一步,单击 Select Configuration Type 窗口下的 MUnit ,然后单击 OK 。
In the last step, click MUnit under Select Configuration Type window, and then click OK.
Running the Test
我们可以运行测试套件以及测试。首先,我们将看到如何运行测试套件。
We can run a test suite as well as a test. First, we will see how to run a test suite.
Running a Test Suite
对于运行测试套件,右键单击你的测试套件所在的 Mule Canvas 空白部分。它会打开一个下拉菜单。现在,单击 Run MUnit suite ,如下所示 −
For running a test suite, right click on the empty part of the Mule Canvas where your test suite resides. It will open a drop-down menu. Now, click on the Run MUnit suite as shown below −
稍后,我们可以在控制台中看到输出。
Later, we can see the output in the console.
Running a Test
要运行特定测试,我们需要选择特定测试并右键单击它。我们将会得到与运行测试套件时相同的下拉菜单。现在,单击 Run MUnit Test 选项,如下所示 −
To run a specific test, we need to select the specific test and right-click on that. We will get the same drop-down menu as we got while running test suite. Now, click on the Run MUnit Test option as shown below −
然后可以在控制台中看到输出。
There after the output can be seen in the console.
Viewing and Analyzing Test Result
Anypoint studio 在左侧资源管理器窗格的 MUnit tab 中显示 MUnit 测试结果。你可以找到绿色成功的测试和红色失败的测试,如下所示 −
Anypoint studio displays the MUnit test result in the MUnit tab of the left-hand explorer pane. You can find successful tests in green color and failed tests in red one as shown below −
我们可以通过查看覆盖率报告来分析我们的测试结果。覆盖率报告的主要功能是提供有关 MUnit 测试集成功执行的 Mule 应用程序的多少的指标。MUnit 覆盖基本上基于执行的 MUnit 消息处理器的数量。MUnit 覆盖报告提供以下指标 −
We can analyze our test result by viewing the coverage report. The main feature of Coverage Report is to provide a metric on how much of a Mule application has been successfully executed by a set of MUnit tests. MUnit coverage is basically based on the amount of MUnit message processors executed. MUnit coverage report provides metric for the following −
-
Application overall coverage
-
Resource coverage
-
Flow coverage
要获得覆盖率报告,我们需要单击 MUnit 选项卡下的“生成报告”,如下所示 −
To get the coverage report, we need to click on ‘Generate Report’ under MUnit tab as shown below −
Debugging the test
我们可以调试一个测试套件以及一个测试。首先,我们将看到如何调试一个测试套件。
We can debug a test suite as well as a test. First, we will see how to debug a test suite.
Debugging a Test Suite
要调试一个测试套件,右键单击存放你的测试套件的 Mule Canvas 空白部分。它会打开一个下拉菜单。现在,单击 Debug MUnit Suite ,如下面的图像所示 −
For debugging a test suite, right click on the empty part of the Mule Canvas where your test suite resides. It will open a drop-down menu. Now, click on the Debug MUnit Suite as shown in the below image −
然后,我们可以在控制台中看到输出。
Then, we can see the output in the console.
Debugging a Test
要调试一个特定测试,我们需要选择特定测试并右键单击它。我们将会得到与调试测试套件时相同的下拉菜单。现在,单击 Debug MUnit Test 选项。它显示在下面屏幕截图中。
To debug a specific test, we need to select the specific test and right-click on that. We will get the same drop-down menu as we got while debugging test suite. Now, click on the Debug MUnit Test option. It is shown in the below screen shot.