INT-2388 Update Gradle build
This is a significant update to the build system, including the changes listed below. README.md has been updated with instructions on the most important day-to-day commands. - Eliminate buildSrc submodule In favor of using the new bundlor and docbook-reference plugins. The net effect is a large reduction in number of lines of build code. Common docbook resources, stylesheets, etc are stored directly in the docbook plugin. This means that --recursive is no longer required when cloning and there will never be a need to use `git submodule` commands. README files have been updated to reflect. Use of the new bundlor plugin also means the removal of template.mf files from the source tree in favor of an inline approach. See build.gradle for details. Bundlor 'import templates' are built up programmatically and kept physically close to gradle dependency declarations, leading to more convenience when changing these values and hopefully fewer errors / version inconsistencies over time. Certain tests depended on the presence of template.mf files, all of which have recently been removed from the source tree in favor of the new bundlor plugin which allows for inlining bundlor configuration within the Gradle build script. These tests now create temp files using the java.io.File API instead. - Upgrade to Gradle 1.0-milestone-6 The m6 release is significantly faster when resolving dependencies and has a number of valuable new features over the earlier m3 version. Review the release notes for Gradle 1.0-milestone-6 online for full details. - Switch to repo.springsource.org repository Previously the project build declared as many repositories as necessary to resolve all project dependencies. Now depending on a single 'virtual repository' defined within the SpringSource Artifactory instance at http://repo.springsource.org. Currently, the virtual repository in use is 'libs-milestone', which allows for the resolution of all "milestone-or-better" versions of all S2 and third-party dependencies. Should snapshot dependencies become required, this value may be changed from 'libs-milestone' to 'libs-snapshot'. To build only against GA releases, change the value to 'libs-release'. - New build plan(s) Spring Integration build plans have been updated to use the Artifactory Bamboo plugin and publish to repo.springsource.org. Build plans have names like 2.1.x to reflect the version under development, not necessarily the name of the branch, as this may change over time and across major releases. - Improve release process As mentioned above, Spring Integration will now use the Artifactory Bamboo plugin to publish releases and also use Artifactory's support for pushing builds directly into Maven Central via oss.sonatype.org. Generate poms that contain all necessary fields for onboarding at Maven central (scm, developers, organization, licenses, etc). Generate -source and -javadoc poms to comply with Maven Central onboarding rules (and for general good practice anyway). Generation of PGP signatures, sha1 and md5 checksums are all handled automatically by Artifactory. These are also requirements for automated entry into Maven Central. - Remove source-level pom generation Automatic generation of Maven poms suitable for use in building Spring Integration is no longer supported. Generation and publication of poms for the purpose of dependency management remains supported. Sonar support has to date depended on these poms, but will be switched over to use the Gradle Sonar plugin shortly. - Eliminate docs subproject Move docs/src to the root of the project and eliminate docs as a formal subproject. This simplifies the build in a number of ways, including removing the need for distinguishing between 'subprojects' and 'javaprojects' as well as allowing users to build both 'api' and 'reference' docs without qualifying with a ':docs' prefix. Also rename the src/info directory to src/dist to better reflect that these files are packaged with the distribution. For example, the readme.txt there is really the distribution readme, distinct from the README.md at the root of the project which is for building from source, etc.
768
src/reference/docbook/aggregator.xml
Normal file
@@ -0,0 +1,768 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="aggregator"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Aggregator</title>
|
||||
|
||||
<section id="aggregator-introduction">
|
||||
<title>Introduction</title>
|
||||
|
||||
<para>Basically a mirror-image of the Splitter, the Aggregator is a type
|
||||
of Message Handler that receives multiple Messages and combines them into
|
||||
a single Message. In fact, an Aggregator is often a downstream consumer in a
|
||||
pipeline that includes a Splitter.</para>
|
||||
|
||||
<para>Technically, the Aggregator is more complex than a Splitter, because
|
||||
it is stateful as it must hold the Messages to be aggregated and determine
|
||||
when the complete group of Messages is ready to be aggregated. In order to do
|
||||
this it requires a <interfacename>MessageStore</interfacename>.</para>
|
||||
</section>
|
||||
|
||||
<section id="aggregator-functionality">
|
||||
<title>Functionality</title>
|
||||
|
||||
<para>The Aggregator combines a group of related messages, by correlating
|
||||
and storing them, until the group is deemed complete. At that point, the
|
||||
Aggregator will create a single message by processing the whole group, and
|
||||
will send the aggregated message as output.</para>
|
||||
|
||||
<para>Implementing an Aggregator requires providing the logic
|
||||
to perform the aggregation (i.e., the creation of a single message
|
||||
from many). Two related concepts are correlation and
|
||||
release.</para>
|
||||
|
||||
<para>Correlation determines how messages are grouped for aggregation.
|
||||
In Spring Integration correlation is done by default based on the CORRELATION_ID message
|
||||
header. Messages with the same CORRELATION_ID will be grouped
|
||||
together. However, the correlation strategy may be customized to allow
|
||||
other ways of specifying how the messages should be grouped together by
|
||||
implementing a <interfacename>CorrelationStrategy</interfacename> (see below).</para>
|
||||
|
||||
<para>To determine the point at which a group of messages is ready to be processed, a
|
||||
<interfacename>ReleaseStrategy</interfacename> is consulted.
|
||||
The default release strategy for the Aggregator will release a group when all
|
||||
messages included in a sequence are present, based on the SEQUENCE_SIZE header.
|
||||
This default strategy may be overridden by providing a reference to a
|
||||
custom <interfacename>ReleaseStrategy</interfacename> implementation.</para>
|
||||
</section>
|
||||
|
||||
<section id="aggregator-api">
|
||||
<title>Programming model</title>
|
||||
|
||||
<para>The Aggregation API consists of a number of classes:</para>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>The interface <interfacename>MessageGroupProcessor</interfacename>, and
|
||||
its subclasses:
|
||||
<classname>MethodInvokingAggregatingMessageGroupProcessor</classname> and
|
||||
<classname>ExpressionEvaluatingMessageGroupProcessor</classname></para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>The <interfacename>ReleaseStrategy</interfacename> interface and its default
|
||||
implementation <classname>SequenceSizeReleaseStrategy</classname></para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>The <interfacename>CorrelationStrategy</interfacename> interface and its default
|
||||
implementation <classname>HeaderAttributeCorrelationStrategy</classname></para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<section>
|
||||
<title>CorrelatingMessageHandler</title>
|
||||
|
||||
<para>The <classname>CorrelatingMessageHandler</classname> is a
|
||||
<interfacename>MessageHandler</interfacename> implementation, encapsulating the common
|
||||
functionalities of an Aggregator (and other correlating use cases),
|
||||
which are: <itemizedlist>
|
||||
<listitem>
|
||||
<para>correlating messages into a group to be aggregated</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>maintaining those messages in a <interfacename>MessageStore</interfacename> until the group
|
||||
can be released</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>deciding when the group can be released</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>aggregating the released group into a single message</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>recognizing and responding to an expired group</para>
|
||||
</listitem>
|
||||
</itemizedlist> The responsibility of deciding how the messages should
|
||||
be grouped together is delegated to a <interfacename>CorrelationStrategy</interfacename>
|
||||
instance. The responsibility of deciding whether the message group can
|
||||
be released is delegated to a <interfacename>ReleaseStrategy</interfacename>
|
||||
instance.</para>
|
||||
|
||||
<para>Here is a brief highlight of the base
|
||||
<classname>AbstractAggregatingMessageGroupProcessor</classname> (the
|
||||
responsibility of implementing the <code>aggregatePayloads</code> method is left to
|
||||
the developer):</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[public abstract class AbstractAggregatingMessageGroupProcessor
|
||||
implements MessageGroupProcessor {
|
||||
|
||||
protected Map<String, Object> aggregateHeaders(MessageGroup group) {
|
||||
// default implementation exists
|
||||
}
|
||||
|
||||
protected abstract Object aggregatePayloads(MessageGroup group, Map<String, Object> defaultHeaders);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
The <interfacename>CorrelationStrategy</interfacename> is owned by the
|
||||
|
||||
<classname>CorrelatingMessageHandler</classname>
|
||||
|
||||
and it has a default value based on the CORRELATION_ID message header:
|
||||
|
||||
<programlisting language="java"><![CDATA[
|
||||
public CorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store,
|
||||
CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) {
|
||||
...
|
||||
this.correlationStrategy = correlationStrategy == null ?
|
||||
new HeaderAttributeCorrelationStrategy(MessageHeaders.CORRELATION_ID) : correlationStrategy;
|
||||
this.releaseStrategy = releaseStrategy == null ? new SequenceSizeReleaseStrategy() : releaseStrategy;
|
||||
...
|
||||
}
|
||||
]]></programlisting>
|
||||
|
||||
<para>As for actual processing of the message group, the default implementation is the
|
||||
<classname>DefaultAggregatingMessageGroupProcessor</classname>. It creates a
|
||||
single Message whose payload is a List of the payloads received for a
|
||||
given group. This works well for simple Scatter Gather implementations with either a Splitter, Publish
|
||||
Subscribe Channel, or Recipient List Router upstream.</para>
|
||||
|
||||
<note>
|
||||
<para>When using a Publish Subscribe Channel or Recipient List Router
|
||||
in this type of scenario, be sure to enable the flag to
|
||||
<code>apply-sequence</code>. That will add the necessary
|
||||
headers (CORRELATION_ID, SEQUENCE_NUMBER and SEQUENCE_SIZE). That
|
||||
behavior is enabled by default for Splitters in Spring Integration,
|
||||
but it is not enabled for the Publish Subscribe Channel or Recipient
|
||||
List Router because those components may be used in a variety of
|
||||
contexts in which these headers are not necessary.</para>
|
||||
</note>
|
||||
|
||||
<para>When implementing a specific aggregator strategy for an application,
|
||||
a developer can extend
|
||||
<classname>AbstractAggregatingMessageGroupProcessor</classname> and implement the
|
||||
<code>aggregatePayloads</code> method. However, there are better solutions, less
|
||||
coupled to the API, for implementing the aggregation logic which can be configured easily
|
||||
either through XML or through annotations.</para>
|
||||
|
||||
<para>In general, any POJO can implement the
|
||||
aggregation algorithm if it provides a method that
|
||||
accepts a single <interfacename>java.util.List</interfacename> as an argument
|
||||
(parameterized lists are supported as well). This method will be invoked for aggregating
|
||||
messages as follows:</para>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>if the argument is a <interfacename>java.util.List<T></interfacename>, and the
|
||||
parameter type T is assignable to <interfacename>Message</interfacename>, then the whole list of
|
||||
messages accumulated for aggregation will be sent to the aggregator</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>if the argument is a non-parameterized <interfacename>java.util.List</interfacename> or the
|
||||
parameter type is not assignable to <interfacename>Message</interfacename>, then the method will
|
||||
receive the payloads of the accumulated messages</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>if the return type is not assignable to <interfacename>Message</interfacename>, then it will
|
||||
be treated as the payload for a Message that will be created
|
||||
automatically by the framework.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<note>
|
||||
<para>In the interest of code simplicity, and promoting best practices
|
||||
such as low coupling, testability, etc., the preferred way of
|
||||
implementing the aggregation logic is through a POJO, and using the
|
||||
XML or annotation support for configuring it in the application.</para>
|
||||
</note>
|
||||
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>ReleaseStrategy</title>
|
||||
|
||||
<para>The <interfacename>ReleaseStrategy</interfacename> interface is defined as
|
||||
follows:</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[public interface ReleaseStrategy {
|
||||
|
||||
boolean canRelease(MessageGroup group);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<para>In general, any POJO can implement the
|
||||
completion decision logic if it provides a method that accepts a single
|
||||
<interfacename>java.util.List</interfacename> as an argument (parameterized lists
|
||||
are supported as well), and returns a boolean value. This method will be
|
||||
invoked after the arrival of each new message, to decide whether the group
|
||||
is complete or not, as follows:</para>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>if the argument is a <interfacename>java.util.List<T></interfacename>, and the
|
||||
parameter type T is assignable to <interfacename>Message</interfacename>, then the whole list of
|
||||
messages accumulated in the group will be sent to the method</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>if the argument is a non-parametrized <interfacename>java.util.List</interfacename> or the
|
||||
parameter type is not assignable to <interfacename>Message</interfacename>, then the method will
|
||||
receive the payloads of the accumulated messages</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>the method must return true if the message group is ready for
|
||||
aggregation, and false otherwise.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
For example:
|
||||
|
||||
<programlisting language="java"><![CDATA[public class MyReleaseStrategy {
|
||||
|
||||
@ReleaseStrategy
|
||||
public boolean canMessagesBeReleased(List<Message<?>>) {...}
|
||||
}]]></programlisting>
|
||||
|
||||
<programlisting language="java"><![CDATA[public class MyReleaseStrategy {
|
||||
|
||||
@ReleaseStrategy
|
||||
public boolean canMessagesBeReleased(List<String>) {...}
|
||||
}]]></programlisting>
|
||||
|
||||
<para>
|
||||
As you can see based on the above signatures, the POJO-based Release Strategy will be passed a <classname>Collection</classname> of unmarked Messages
|
||||
if you need access to the whole <classname>Message</classname> or <classname>Collection</classname> of payload objects if the type parameter is
|
||||
anything other than <classname>Message</classname>. Typically this would satisfy the majority of use cases. However if
|
||||
for some reason you need to access the full <classname>MessageGroup</classname> - which contains <code>unmarked</code> and <code>marked</code> Messages -
|
||||
then you should simply provide an implementation of the <classname>ReleaseStrategy</classname> interface.
|
||||
</para>
|
||||
|
||||
<para>When the group is released for aggregation, all its unmarked
|
||||
messages are processed and then marked so they will not be processed
|
||||
again. If the group is also complete (i.e. if all messages from a
|
||||
sequence have arrived or if there is no sequence defined), then the group
|
||||
is removed from the message store. Partial sequences can be released, in
|
||||
which case the next time the <interfacename>ReleaseStrategy</interfacename> is called it
|
||||
will be presented with a group containing marked messages (already
|
||||
processed) and unmarked messages (potentially a new partial
|
||||
sequence).</para>
|
||||
|
||||
<para>Spring Integration provides an out-of-the box implementation for
|
||||
<interfacename>ReleaseStrategy</interfacename>, the
|
||||
<classname>SequenceSizeReleaseStrategy</classname>. This implementation consults the
|
||||
SEQUENCE_NUMBER and SEQUENCE_SIZE headers of each arriving message to decide
|
||||
when a message group is complete and ready to be aggregated. As shown
|
||||
above, it is also the default strategy.</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>CorrelationStrategy</title>
|
||||
|
||||
<para>The <interfacename>CorrelationStrategy</interfacename> interface is defined as
|
||||
follows:</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[public interface CorrelationStrategy {
|
||||
|
||||
Object getCorrelationKey(Message<?> message);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<para>The method returns an Object which represents the correlation key
|
||||
used for associating the message with a message group. The key must satisfy the
|
||||
criteria used for a key in a Map with respect to the implementation of
|
||||
equals() and hashCode().</para>
|
||||
|
||||
<para>In general, any POJO can implement the
|
||||
correlation logic, and the rules for mapping a message to a
|
||||
method's argument (or arguments) are the same as for a
|
||||
<interfacename>ServiceActivator</interfacename> (including support for @Header
|
||||
annotations). The method must return a value, and the value must not be
|
||||
<code>null</code>.</para>
|
||||
|
||||
<para>Spring Integration provides an out-of-the box implementation for
|
||||
<interfacename>CorrelationStrategy</interfacename>, the
|
||||
<classname>HeaderAttributeCorrelationStrategy</classname>. This implementation
|
||||
returns the value of one of the message headers (whose name is specified
|
||||
by a constructor argument) as the correlation key. By default, the
|
||||
correlation strategy is a <classname>HeaderAttributeCorrelationStrategy</classname> returning
|
||||
the value of the CORRELATION_ID header attribute. If you have a custom header name
|
||||
you would like to use for correlation, then simply configure that on an instance of
|
||||
<classname>HeaderAttributeCorrelationStrategy</classname> and provide that as a
|
||||
reference for the Aggregator's correlation-strategy.</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="aggregator-config">
|
||||
<title>Configuring Aggregator</title>
|
||||
<section id="aggregator-xml">
|
||||
<title>Configuring an Aggregator with XML</title>
|
||||
|
||||
<para>Spring Integration supports the configuration of an aggregator via
|
||||
XML through the <aggregator/> element. Below you can see an example
|
||||
of an aggregator.</para>
|
||||
|
||||
<programlisting lang="xml"><![CDATA[<channel id="inputChannel"/>
|
||||
|
||||
|
||||
<int:aggregator id="myAggregator" ]]><co id="aggxml01" /><![CDATA[
|
||||
auto-startup="true" ]]><co id="aggxml02" /><![CDATA[
|
||||
input-channel="inputChannel" ]]><co id="aggxml03" /><![CDATA[
|
||||
output-channel="outputChannel" ]]><co id="aggxml04" /><![CDATA[
|
||||
discard-channel="throwAwayChannel" ]]><co id="aggxml05" /><![CDATA[
|
||||
message-store="persistentMessageStore" ]]><co id="aggxml06" /><![CDATA[
|
||||
order="1" ]]><co id="aggxml07" /><![CDATA[
|
||||
send-partial-result-on-expiry="false" ]]><co id="aggxml08" /><![CDATA[
|
||||
send-timeout="1000" ]]><co id="aggxml09" /><![CDATA[
|
||||
|
||||
correlation-strategy="correlationStrategyBean" ]]><co id="aggxml10" /><![CDATA[
|
||||
correlation-strategy-method="correlate" ]]><co id="aggxml11" /><![CDATA[
|
||||
|
||||
ref="aggregatorBean" ]]><co id="aggxml12" /><![CDATA[
|
||||
method="aggregate" ]]><co id="aggxml13" /><![CDATA[
|
||||
|
||||
release-strategy="releaseStrategyBean" ]]><co id="aggxml14" /><![CDATA[
|
||||
release-strategy-method="release"/> ]]><co id="aggxml15" /><![CDATA[
|
||||
|
||||
|
||||
<int:channel id="outputChannel"/>
|
||||
|
||||
<int:channel id="throwAwayChannel"/>
|
||||
|
||||
<bean id="persistentMessageStore" class="org.springframework.integration.jdbc.JdbcMessageStore">
|
||||
<constructor-arg ref="dataSource"/>
|
||||
</bean>
|
||||
|
||||
<bean id="aggregatorBean" class="sample.PojoAggregator"/>
|
||||
|
||||
<bean id="releaseStrategyBean" class="sample.PojoReleaseStrategy"/>
|
||||
|
||||
<bean id="correlationStrategyBean" class="sample.PojoCorrelationStrategy"/>]]></programlisting>
|
||||
|
||||
<calloutlist>
|
||||
<callout arearefs="aggxml01">
|
||||
<para>The id of the aggregator is
|
||||
<emphasis>0ptional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml02">
|
||||
<para>Lifecycle attribute signaling if aggregator should be started during Application Context startup.
|
||||
<emphasis>Optional (default is 'true')</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml03">
|
||||
<para>The channel from which where aggregator will receive messages.
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml04">
|
||||
<para>The channel to which the aggregator will send the aggregation
|
||||
results. <emphasis>Optional (because incoming messages can specify a
|
||||
reply channel themselves via 'replyChannel' Message Header)</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml05">
|
||||
<para>The channel to which the aggregator will send the messages that
|
||||
timed out (if <code>send-partial-result-on-expiry</code> is
|
||||
<emphasis>false</emphasis>). <emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml06">
|
||||
<para>A reference to a <code>MessageGroupStore</code> used
|
||||
to store groups of messages under their correlation key until they are
|
||||
complete. <emphasis>Optional</emphasis>, by default a volatile
|
||||
in-memory store.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml07">
|
||||
<para>Order of this aggregator when more than one handle is subscribed to the same DirectChannel
|
||||
(use for load balancing purposes).
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml08">
|
||||
<para>
|
||||
Indicates that expired messages should be aggregated and sent to the 'output-channel' or 'replyChannel'
|
||||
once their containing <classname>MessageGroup</classname> is expired (see <code>MessageGroupStore.expireMessageGroups(long)</code>).
|
||||
One way of expiring <classname>MessageGroup</classname>s is by configuring a <classname>MessageGroupStoreReaper</classname>.
|
||||
However <classname>MessageGroup</classname>s can alternatively be expired by simply calling
|
||||
<code>MessageGroupStore.expireMessageGroup(groupId)</code>. That could be accomplished via a Control Bus operation
|
||||
or by simply invoking that method if you have a reference to the <classname>MessageGroupStore</classname> instance.
|
||||
Otherwise by itself this attribute has no behavior. It only serves as an indicator of what to do (discard or send to the output/reply
|
||||
channel) with Messages that are still in the <classname>MessageGroup</classname> that is about to be expired.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
<para><emphasis>Default - 'false'</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml09">
|
||||
<para>The timeout interval for sending the aggregated messages to the output or
|
||||
reply channel. <emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml10">
|
||||
<para>A reference to a bean that implements the message correlation (grouping)
|
||||
algorithm. The bean can be an implementation of the <interfacename>CorrelationStrategy</interfacename>
|
||||
interface or a POJO. In the latter case the correlation-strategy-method attribute must be defined
|
||||
as well. <emphasis>Optional (by default, the aggregator will use
|
||||
the CORRELATION_ID header) </emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml11">
|
||||
<para>A method defined on the bean referenced by
|
||||
<code>correlation-strategy</code>, that implements the
|
||||
correlation decision algorithm. <emphasis>Optional, with
|
||||
restrictions (requires <code>correlation-strategy</code> to be
|
||||
present).</emphasis></para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml12">
|
||||
<para>A reference to a bean defined in the application context. The bean must implement the aggregation logic
|
||||
as described above. <emphasis>Optional (by default the list of aggregated Messages will become a
|
||||
payload of the output message).</emphasis></para>
|
||||
</callout>
|
||||
<callout arearefs="aggxml13">
|
||||
<para>A method defined on the bean referenced by <code>ref</code>,
|
||||
that implements the message aggregation
|
||||
algorithm. <emphasis>Optional, depends on <code>ref</code> attribute being defined.</emphasis></para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml14">
|
||||
<para>A reference to a bean that implements the release strategy.
|
||||
The bean can be an implementation of the <interfacename>ReleaseStrategy</interfacename> interface
|
||||
or a POJO. In the latter case the release-strategy-method
|
||||
attribute must be defined as well. <emphasis>Optional (by default, the
|
||||
aggregator will use the SEQUENCE_SIZE header attribute)</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="aggxml15">
|
||||
<para>A method defined on the bean referenced by
|
||||
<code>release-strategy</code>, that implements the
|
||||
completion decision algorithm. <emphasis>Optional, with
|
||||
restrictions (requires <code>release-strategy</code> to be
|
||||
present).</emphasis></para>
|
||||
</callout>
|
||||
|
||||
</calloutlist>
|
||||
|
||||
<para>Using a <code>ref</code> attribute is generally recommended if a custom
|
||||
aggregator handler implementation may be referenced in other
|
||||
<code><aggregator></code> definitions. However if a custom
|
||||
aggregator implementation is only being used by a single
|
||||
definition of the <code><aggregator></code>, you can use an inner
|
||||
bean definition (starting with version 1.0.3) to configure the aggregation
|
||||
POJO within the <code><aggregator></code> element:
|
||||
<programlisting language="xml"><![CDATA[<aggregator input-channel="input" method="sum" output-channel="output">
|
||||
<beans:bean class="org.foo.PojoAggregator"/>
|
||||
</aggregator>]]></programlisting></para>
|
||||
|
||||
<note>
|
||||
<para>Using both a <code>ref</code> attribute and an inner bean definition in the
|
||||
same <code><aggregator></code> configuration is not allowed, as it
|
||||
creates an ambiguous condition. In such cases, an Exception will be
|
||||
thrown.</para>
|
||||
</note>
|
||||
|
||||
<para>An example implementation of the aggregator bean looks as
|
||||
follows:</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[public class PojoAggregator {
|
||||
|
||||
public Long add(List<Long> results) {
|
||||
long total = 0l;
|
||||
for (long partialResult: results) {
|
||||
total += partialResult;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<para>An implementation of the completion strategy bean for the example
|
||||
above may be as follows:</para>
|
||||
|
||||
<para><programlisting language="java"><![CDATA[public class PojoReleaseStrategy {
|
||||
...
|
||||
public boolean canRelease(List<Long> numbers) {
|
||||
int sum = 0;
|
||||
for (long number: numbers) {
|
||||
sum += number;
|
||||
}
|
||||
return sum >= maxValue;
|
||||
}
|
||||
}]]></programlisting> <note>
|
||||
<para>Wherever it makes sense, the release strategy method and the
|
||||
aggregator method can be combined in a single bean.</para>
|
||||
</note></para>
|
||||
|
||||
<para>An implementation of the correlation strategy bean for the example
|
||||
above may be as follows:</para>
|
||||
|
||||
<para><programlisting language="java"><![CDATA[public class PojoCorrelationStrategy {
|
||||
...
|
||||
public Long groupNumbersByLastDigit(Long number) {
|
||||
return number % 10;
|
||||
}
|
||||
}]]></programlisting></para>
|
||||
|
||||
<para>For example, this aggregator would group numbers by some criterion
|
||||
(in our case the remainder after dividing by 10) and will hold the group
|
||||
until the sum of the numbers provided by the payloads exceeds a
|
||||
certain value.</para>
|
||||
|
||||
<note>
|
||||
<para>Wherever it makes sense, the release strategy method, correlation
|
||||
strategy method and the aggregator method can be combined in a single
|
||||
bean (all of them or any two).</para>
|
||||
</note>
|
||||
|
||||
<para>
|
||||
<emphasis>Aggregators and Spring Expression Language (SpEL)</emphasis>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Since Spring Integration 2.0, the various strategies (correlation, release, and aggregation) may be handled with
|
||||
<ulink url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html">SpEL</ulink>
|
||||
which is recommended if the logic behind such <emphasis>release strategy</emphasis> is relatively simple.
|
||||
Let's say you have a legacy component that was designed to receive an array of objects. We know that the default release
|
||||
strategy will assemble all aggregated messages in the List. So now we have two problems. First we need to extract
|
||||
individual messages from the list, and then we need to extract the payload of each message and assemble
|
||||
the array of objects (see code below).
|
||||
|
||||
<programlisting language="java"><![CDATA[public String[] processRelease(List<Message<String>> messages){
|
||||
List<String> stringList = new ArrayList<String>();
|
||||
for (Message<String> message : messages) {
|
||||
stringList.add(message.getPayload());
|
||||
}
|
||||
return stringList.toArray(new String[]{});
|
||||
}]]></programlisting>
|
||||
|
||||
However, with SpEL such a requirement could actually be handled relatively easily with a
|
||||
one-line expression, thus sparing you from writing a custom class and configuring it as a bean.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:aggregator input-channel="aggChannel"
|
||||
output-channel="replyChannel"
|
||||
expression="#this.![payload].toArray()"/>]]></programlisting>
|
||||
|
||||
In the above configuration we are using a <ulink
|
||||
url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html#d0e12113">Collection Projection</ulink> expression
|
||||
to assemble a new collection from the payloads of all messages in the list and then transforming it to an Array, thus
|
||||
achieving the same result as the java code above.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The same expression-based approach can be applied when dealing with custom <emphasis>Release</emphasis> and
|
||||
<emphasis>Correlation</emphasis> strategies.
|
||||
</para>
|
||||
<para>
|
||||
Instead of defining a bean for a custom <classname>CorrelationStrategy</classname> via
|
||||
the <code>correlation-strategy</code> attribute, you can implement your simple correlation logic
|
||||
via a SpEL expression and configure it via the <code>correlation-strategy-expression</code> attribute.
|
||||
</para>
|
||||
<para>
|
||||
For example:
|
||||
|
||||
<programlisting language="xml"><![CDATA[correlation-strategy-expression="payload.person.id"]]></programlisting>
|
||||
|
||||
In the above example it is assumed that the payload has an attribute <code>person</code> with an <code>id</code>
|
||||
which is going to be used to correlate messages.
|
||||
</para>
|
||||
<para>
|
||||
Likewise, for the <interfacename>ReleaseStrategy</interfacename> you can implement your release logic as
|
||||
a SpEL expression and configure it via the <code>release-strategy-expression</code> attribute.
|
||||
The only difference is that since ReleaseStrategy is passed the List of Messages, the root object in the SpEL
|
||||
evaluation context is the List itself. That List can be referenced as <code>#this</code> within the expression.
|
||||
</para>
|
||||
<para>
|
||||
For example:
|
||||
|
||||
<programlisting language="xml"><![CDATA[release-strategy-expression="#this.size() gt 5"]]></programlisting>
|
||||
|
||||
In this example the root object of the SpEL Evaluation Context is the
|
||||
<interfacename>MessageGroup</interfacename> itself, and you are simply stating
|
||||
that as soon as there are more than 5 messages in this group, it should be released.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="aggregator-annotations">
|
||||
<title>Configuring an Aggregator with Annotations</title>
|
||||
|
||||
<para>An aggregator configured using annotations would look like this.</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[public class Waiter {
|
||||
...
|
||||
|
||||
@Aggregator ]]><co id="aggann" /><![CDATA[
|
||||
public Delivery aggregatingMethod(List<OrderItem> items) {
|
||||
...
|
||||
}
|
||||
|
||||
@ReleaseStrategy ]]><co id="agganncs" /><![CDATA[
|
||||
public boolean releaseChecker(List<Message<?>> messages) {
|
||||
...
|
||||
}
|
||||
|
||||
@CorrelationStrategy ]]><co id="agganncorrs" /><![CDATA[
|
||||
public String correlateBy(OrderItem item) {
|
||||
...
|
||||
}
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<calloutlist>
|
||||
<callout arearefs="aggann">
|
||||
<para>An annotation indicating that this method shall be used as an
|
||||
aggregator. Must be specified if this class will be used as an
|
||||
aggregator.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="agganncs">
|
||||
<para id="aggann2">An annotation indicating that this method shall be
|
||||
used as the release strategy of an aggregator. If not present on any
|
||||
method, the aggregator will use the
|
||||
SequenceSizeReleaseStrategy.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="agganncorrs">
|
||||
<para id="agann3">An annotation indicating that this method shall be
|
||||
used as the correlation strategy of an aggregator. If no correlation
|
||||
strategy is indicated, the aggregator will use the
|
||||
HeaderAttributeCorrelationStrategy based on CORRELATION_ID.</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
|
||||
<para>All of the configuration options provided by the xml element are
|
||||
also available for the @Aggregator annotation.</para>
|
||||
|
||||
<para>The aggregator can be either referenced explicitly from XML or, if
|
||||
the @MessageEndpoint is defined on the class, detected automatically
|
||||
through classpath scanning.</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title id="reaper">Managing State in an Aggregator:
|
||||
MessageGroupStore</title>
|
||||
|
||||
<para>Aggregator (and some other patterns in Spring Integration) is a
|
||||
stateful pattern that requires decisions to be made based on a group of
|
||||
messages that have arrived over a period of time, all with the same
|
||||
correlation key. The design of the interfaces in the stateful patterns
|
||||
(e.g. <interfacename>ReleaseStrategy</interfacename>) is driven by the principle
|
||||
that the components (whether defined by the framework or a user) should be able to remain stateless.
|
||||
All state is carried by the <interfacename>MessageGroup</interfacename> and its
|
||||
management is delegated to the
|
||||
<interfacename>MessageGroupStore</interfacename>.
|
||||
|
||||
|
||||
<programlisting><![CDATA[public interface MessageGroupStore {
|
||||
int getMessageCountForAllMessageGroups();
|
||||
|
||||
int getMarkedMessageCountForAllMessageGroups();
|
||||
|
||||
int getMessageGroupCount();
|
||||
|
||||
MessageGroup getMessageGroup(Object groupId);
|
||||
|
||||
MessageGroup addMessageToGroup(Object groupId, Message<?> message);
|
||||
|
||||
MessageGroup markMessageGroup(MessageGroup group);
|
||||
|
||||
MessageGroup removeMessageFromGroup(Object key, Message<?> messageToRemove);
|
||||
|
||||
MessageGroup markMessageFromGroup(Object key, Message<?> messageToMark);
|
||||
|
||||
void removeMessageGroup(Object groupId);
|
||||
|
||||
void registerMessageGroupExpiryCallback(MessageGroupCallback callback);
|
||||
|
||||
int expireMessageGroups(long timeout);
|
||||
}]]></programlisting>
|
||||
|
||||
For more information please refer to the
|
||||
<ulink url="http://static.springsource.org/spring-integration/api/org/springframework/integration/store/MessageGroupStore.html">JavaDoc</ulink>.
|
||||
</para>
|
||||
|
||||
<para>The <interfacename>MessageGroupStore</interfacename> accumulates state
|
||||
information in <interfacename>MessageGroups</interfacename> while waiting for
|
||||
a release strategy to be triggered, and that event might not ever happen.
|
||||
So to prevent stale messages from lingering, and for volatile stores to
|
||||
provide a hook for cleaning up when the application shuts down, the
|
||||
<interfacename>MessageGroupStore</interfacename> allows the user to register
|
||||
callbacks to apply to its <interfacename>MessageGroups</interfacename> when they
|
||||
expire. The interface is very straightforward:</para>
|
||||
|
||||
<programlisting><![CDATA[public interface MessageGroupCallback {
|
||||
|
||||
void execute(MessageGroupStore messageGroupStore, MessageGroup group);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<para>The callback has direct access to the store and the message group
|
||||
so it can manage the persistent state (e.g. by removing the group from the
|
||||
store entirely).</para>
|
||||
|
||||
<para>The <interfacename>MessageGroupStore</interfacename> maintains a list of these callbacks
|
||||
which it applies, on demand, to all messages whose timestamp is earlier than a time
|
||||
supplied as a parameter (see the <methodname>registerMessageGroupExpiryCallback(..)</methodname>
|
||||
and <methodname>expireMessageGroups(..)</methodname> methods above).</para>
|
||||
|
||||
<para>The <code>expireMessageGroups</code> method can be called with a timeout value.
|
||||
Any message older than the current time minus this value will be expired,
|
||||
and have the callbacks applied. Thus it is the user of the store that
|
||||
defines what is meant by message group "expiry".</para>
|
||||
|
||||
<para>As a convenience for users, Spring Integration provides a wrapper
|
||||
for the message expiry in the form of a
|
||||
<classname>MessageGroupStoreReaper</classname>:</para>
|
||||
|
||||
<programlisting><![CDATA[<bean id="reaper" class="org...MessageGroupStoreReaper">
|
||||
<property name="messageGroupStore" ref="messageStore"/>
|
||||
<property name="timeout" value="30000"/>
|
||||
</bean>
|
||||
|
||||
<task:scheduled-tasks scheduler="scheduler">
|
||||
<task:scheduled ref="reaper" method="run" fixed-rate="10000"/>
|
||||
</task:scheduled-tasks>]]></programlisting>
|
||||
|
||||
<para>The reaper is a <interfacename>Runnable</interfacename>, and all that is happening
|
||||
in the example above is that the message group store's expire method is being called
|
||||
once every 10 seconds. The timeout itself is 30 seconds.</para>
|
||||
|
||||
<note>
|
||||
It is important to understand that the 'timeout' property of the <classname>MessageGroupStoreReaper</classname> is an
|
||||
approximate value and is impacted by the the rate of the task scheduler since this property will
|
||||
only be checked on the next scheduled execution of the <classname>MessageGroupStoreReaper</classname> task. For example if
|
||||
the timeout is set for 10 min, but the <classname>MessageGroupStoreReaper</classname> task is scheduled to run every 60 min
|
||||
and the last execution of the <classname>MessageGroupStoreReaper</classname> task happened 1 min before the timeout, the
|
||||
<classname>MessageGroup</classname> will not expire for the next 59 min. So it is recommended to set the rate at least equal to the value of the timeout or shorter.
|
||||
</note>
|
||||
|
||||
<para>In addition to the reaper, the expiry callbacks are invoked when the application
|
||||
shuts down via a lifecycle callback in the <classname>CorrelatingMessageHandler</classname>.
|
||||
</para>
|
||||
|
||||
<para>The <classname>CorrelatingMessageHandler</classname> registers its
|
||||
own expiry callback, and this is the link with the boolean flag
|
||||
<code>send-partial-result-on-expiry</code> in the XML configuration of the
|
||||
aggregator. If the flag is set to true, then when the expiry callback is
|
||||
invoked, any unmarked messages in groups that are not yet released can
|
||||
be sent on to the output channel.</para>
|
||||
</section>
|
||||
</section>
|
||||
515
src/reference/docbook/amqp.xml
Normal file
@@ -0,0 +1,515 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="amqp"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>AMQP Support</title>
|
||||
|
||||
<section id="amqp-introduction">
|
||||
<title>Introduction</title>
|
||||
|
||||
<para>
|
||||
Spring Integration provides Channel Adapters for receiving and sending
|
||||
messages using the Advanced Message Queuing Protocol (AMQP).
|
||||
|
||||
The following adapters are available:
|
||||
<itemizedlist>
|
||||
<listitem>Inbound Channel Adapter</listitem>
|
||||
<listitem>Outbound Channel Adapter</listitem>
|
||||
<listitem>Inbound Gateway</listitem>
|
||||
<listitem>Outbound Gateway</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
Spring Integration also provides a point-to-point Message Channel as well as a
|
||||
publish/subscribe Message Channel backed by AMQP Exchanges and Queues.
|
||||
</para>
|
||||
<para>
|
||||
In order to provide AMQP support, Spring Integration relies on Spring AMQP
|
||||
(<ulink url="http://www.springsource.org/spring-amqp">http://www.springsource.org/spring-amqp</ulink>)
|
||||
which "applies core Spring concepts to the development of AMQP-based
|
||||
messaging solutions". Spring AMQP provides similar semantics as Spring JMS
|
||||
(<ulink url="http://static.springsource.org/spring/docs/current/spring-framework-reference/htmlsingle/spring-framework-reference.html#jms">http://.../spring-framework-reference.html#jms</ulink>).
|
||||
</para>
|
||||
<para>
|
||||
Whereas the provided AMQP Channel Adapters are intended for unidirectional
|
||||
Messaging (send or receive) only, Spring Integration also provides inbound
|
||||
and outbound AMQP Gateways for request/reply operations.
|
||||
</para>
|
||||
<tip>
|
||||
<para>
|
||||
Please familiarize yourself with the reference documentation of
|
||||
the Spring AMQP project as well. It provides much more in-depth information
|
||||
regarding Spring's integration with AMQP in general and RabbitMQ in
|
||||
particular.</para>
|
||||
<para>You can find the documentation at:
|
||||
<ulink url="http://static.springsource.org/spring-amqp/docs/1.0.x/reference/html/">
|
||||
http://static.springsource.org/spring-amqp/docs/1.0.x/reference/html/</ulink>
|
||||
</para>
|
||||
</tip>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Inbound Channel Adapter</title>
|
||||
|
||||
<para>A configuration sample for an AMQP Inbound Channel Adapter is shown
|
||||
below with all available parameters.</para>
|
||||
<programlisting language="xml"><![CDATA[<int-amqp:inbound-channel-adapter id="inboundAmqp"]]><co id="amqp-inbound-channel-adapter-xml-01-co" linkends="amqp-inbound-channel-adapter-xml-01" /><![CDATA[
|
||||
channel="inboundChannel"]]><co id="amqp-inbound-channel-adapter-xml-02-co" linkends="amqp-inbound-channel-adapter-xml-02" /><![CDATA[
|
||||
queue-names="si.test.queue"]]><co id="amqp-inbound-channel-adapter-xml-03-co" linkends="amqp-inbound-channel-adapter-xml-03" /><![CDATA[
|
||||
acknowledge-mode="AUTO"]]><co id="amqp-inbound-channel-adapter-xml-04-co" linkends="amqp-inbound-channel-adapter-xml-04" /><![CDATA[
|
||||
advice-chain=""]]><co id="amqp-inbound-channel-adapter-xml-05-co" linkends="amqp-inbound-channel-adapter-xml-05" /><![CDATA[
|
||||
channel-transacted=""]]><co id="amqp-inbound-channel-adapter-xml-06-co" linkends="amqp-inbound-channel-adapter-xml-06" /><![CDATA[
|
||||
concurrent-consumers=""]]><co id="amqp-inbound-channel-adapter-xml-07-co" linkends="amqp-inbound-channel-adapter-xml-07" /><![CDATA[
|
||||
connection-factory=""]]><co id="amqp-inbound-channel-adapter-xml-08-co" linkends="amqp-inbound-channel-adapter-xml-08" /><![CDATA[
|
||||
error-channel=""]]><co id="amqp-inbound-channel-adapter-xml-09-co" linkends="amqp-inbound-channel-adapter-xml-09" /><![CDATA[
|
||||
expose-listener-channel=""]]><co id="amqp-inbound-channel-adapter-xml-10-co" linkends="amqp-inbound-channel-adapter-xml-10" /><![CDATA[
|
||||
header-mapper=""]]><co id="amqp-inbound-channel-adapter-xml-11-co" linkends="amqp-inbound-channel-adapter-xml-11" /><![CDATA[
|
||||
mapped-request-headers=""]]><co id="amqp-inbound-channel-adapter-xml-12-co" linkends="amqp-inbound-channel-adapter-xml-12" /><![CDATA[
|
||||
mapped-reply-headers=""]]><co id="amqp-inbound-channel-adapter-xml-13-co" linkends="amqp-inbound-channel-adapter-xml-13" /><![CDATA[
|
||||
listener-container=""]]><co id="amqp-inbound-channel-adapter-xml-14-co" linkends="amqp-inbound-channel-adapter-xml-14" /><![CDATA[
|
||||
message-converter=""]]><co id="amqp-inbound-channel-adapter-xml-15-co" linkends="amqp-inbound-channel-adapter-xml-15" /><![CDATA[
|
||||
message-properties-converter=""]]><co id="amqp-inbound-channel-adapter-xml-16-co" linkends="amqp-inbound-channel-adapter-xml-16" /><![CDATA[
|
||||
phase=""]]><co id="amqp-inbound-channel-adapter-xml-17-co" linkends="amqp-inbound-channel-adapter-xml-17" /><![CDATA[
|
||||
prefetch-count=""]]><co id="amqp-inbound-channel-adapter-xml-18-co" linkends="amqp-inbound-channel-adapter-xml-18" /><![CDATA[
|
||||
receive-timeout=""]]><co id="amqp-inbound-channel-adapter-xml-19-co" linkends="amqp-inbound-channel-adapter-xml-19" /><![CDATA[
|
||||
recovery-interval=""]]><co id="amqp-inbound-channel-adapter-xml-20-co" linkends="amqp-inbound-channel-adapter-xml-20" /><![CDATA[
|
||||
shutdown-timeout=""]]><co id="amqp-inbound-channel-adapter-xml-21-co" linkends="amqp-inbound-channel-adapter-xml-21" /><![CDATA[
|
||||
task-executor=""]]><co id="amqp-inbound-channel-adapter-xml-22-co" linkends="amqp-inbound-channel-adapter-xml-22" /><![CDATA[
|
||||
transaction-attribute=""]]><co id="amqp-inbound-channel-adapter-xml-23-co" linkends="amqp-inbound-channel-adapter-xml-23" /><![CDATA[
|
||||
transaction-manager=""]]><co id="amqp-inbound-channel-adapter-xml-24-co" linkends="amqp-inbound-channel-adapter-xml-24" /><![CDATA[
|
||||
tx-size=""]]><co id="amqp-inbound-channel-adapter-xml-25-co" linkends="amqp-inbound-channel-adapter-xml-25" /><![CDATA[/>]]>
|
||||
</programlisting>
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-01-co" id="amqp-inbound-channel-adapter-xml-01">
|
||||
<para>Unique ID for this adapter.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-02-co" id="amqp-inbound-channel-adapter-xml-02">
|
||||
<para>Message Channel to which converted Messages should be sent.
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-03-co" id="amqp-inbound-channel-adapter-xml-03">
|
||||
<para>Names of the AMQP Queues from which Messages should be
|
||||
consumed (comma-separated list).
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-04-co" id="amqp-inbound-channel-adapter-xml-04">
|
||||
<para>Acknowledge Mode for the <interface>MessageListenerContainer</interface>.
|
||||
<emphasis>Optional (Defaults to AUTO)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-05-co" id="amqp-inbound-channel-adapter-xml-05">
|
||||
<para>Extra AOP Advice(s) to handle cross cutting behavior associated with this Inbound Channel Adapter.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-06-co" id="amqp-inbound-channel-adapter-xml-06">
|
||||
<para>Flag to indicate that channels created by this component
|
||||
will be transactional. Ff true, tells the framework to use
|
||||
a transactional channel and to end all operations (send or
|
||||
receive) with a commit or rollback depending on the outcome,
|
||||
with an exception signalling a rollback.
|
||||
<emphasis>Optional (Defaults to false)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-07-co" id="amqp-inbound-channel-adapter-xml-07">
|
||||
<para>Specify the number of concurrent consumers to create.
|
||||
Default is 1. Raising the number of concurrent consumers
|
||||
is recommended in order to scale the consumption of
|
||||
messages coming in from a queue. However, note that any
|
||||
ordering guarantees are lost once multiple consumers are
|
||||
registered. In general, stick with 1 consumer for
|
||||
low-volume queues.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-08-co" id="amqp-inbound-channel-adapter-xml-08">
|
||||
<para>Bean reference to the RabbitMQ ConnectionFactory.
|
||||
<emphasis>Optional (Defaults to 'connectionFactory')</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-09-co" id="amqp-inbound-channel-adapter-xml-09">
|
||||
<para>Message Channel to which error Messages should be sent.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-10-co" id="amqp-inbound-channel-adapter-xml-10">
|
||||
<para>Shall the listener channel (com.rabbitmq.client.Channel) be
|
||||
exposed to a registered <interface>ChannelAwareMessageListener</interface>.
|
||||
<emphasis>Optional (Defaults to true)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-11-co" id="amqp-inbound-channel-adapter-xml-11">
|
||||
<para><classname>HeaderMapper</classname> to use when receiving AMQP Messages.
|
||||
<emphasis>Optional</emphasis>.
|
||||
By default only standard AMQP properties (e.g. contentType) will be copied to and from
|
||||
Spring Integration MessageHeaders. Any user-defined headers within the AMQP
|
||||
MessageProperties will NOT be copied to or from an AMQP Message unless
|
||||
explicitly identified via 'requestHeaderNames' and/or 'replyHeaderNames' properties of this <classname>HeaderMapper</classname>.
|
||||
If you need to copy all user-defined headers simply use wild-card character '*'.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-12-co" id="amqp-inbound-channel-adapter-xml-12">
|
||||
<para>Comma-separated list of names of AMQP Headers to be mapped from the AMQP request into the MessageHeaders.
|
||||
This can only be provided if the 'header-mapper' reference is not being set directly. The values in
|
||||
this list can also be simple patterns to be matched against the header names (e.g. "*" or "foo*, bar" or "*foo").</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-13-co" id="amqp-inbound-channel-adapter-xml-13">
|
||||
<para>Comma-separated list of names of MessageHeaders to be mapped into the AMQP Message Properties of the AMQP reply message.
|
||||
All standard Headers (e.g., contentType) will be mapped to AMQP Message Properties while user-defined headers will be mapped to 'headers' property
|
||||
which itself is a Map.
|
||||
This can only be provided if the 'header-mapper' reference is not being set directly. The values in
|
||||
this list can also be simple patterns to be matched against the header names (e.g. "*" or "foo*, bar" or "*foo").</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-14-co" id="amqp-inbound-channel-adapter-xml-14">
|
||||
<para>Reference to the <interface>SimpleMessageListenerContainer</interface>
|
||||
to use for receiving AMQP Messages. If this attribute is provided,
|
||||
then no other attribute related to the listener container
|
||||
configuration should be provided. In other words, by
|
||||
setting this reference, you must take full responsibility
|
||||
of the listener container configuration. The only exception
|
||||
is the MessageListener itself. Since that is actually the
|
||||
core responsibility of this Channel Adapter implementation,
|
||||
the referenced listener container must NOT already have its
|
||||
own MessageListener configured.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-15-co" id="amqp-inbound-channel-adapter-xml-15">
|
||||
<para>The MessageConverter to use when receiving AMQP Messages.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-16-co" id="amqp-inbound-channel-adapter-xml-16">
|
||||
<para>The MessagePropertiesConverter to use when receiving AMQP Messages.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-17-co" id="amqp-inbound-channel-adapter-xml-17">
|
||||
<para>Specify the phase in which the underlying <interface>SimpleMessageListenerContainer</interface>
|
||||
should be started and stopped. The startup order proceeds
|
||||
from lowest to highest, and the shutdown order is the
|
||||
reverse of that. By default this value is Integer.MAX_VALUE
|
||||
meaning that this container starts as late as possible and
|
||||
stops as soon as possible.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-18-co" id="amqp-inbound-channel-adapter-xml-18">
|
||||
<para>Tells the AMQP broker how many messages to send to each
|
||||
consumer in a single request. Often this can be set quite
|
||||
high to improve throughput. It should be greater than or
|
||||
equal to the transaction size (see attribute "tx-size").
|
||||
<emphasis>Optional (Defaults to 1)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-19-co" id="amqp-inbound-channel-adapter-xml-19">
|
||||
<para>Receive timeout in milliseconds.
|
||||
<emphasis>Optional (Defaults to 1000)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-20-co" id="amqp-inbound-channel-adapter-xml-20">
|
||||
<para>Specifies the interval between recovery attempts of the underlying
|
||||
<interface>SimpleMessageListenerContainer</interface> (in
|
||||
milliseconds).
|
||||
<emphasis>Optional (Defaults to 5000)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-21-co" id="amqp-inbound-channel-adapter-xml-21">
|
||||
<para>The time to wait for workers in milliseconds after the
|
||||
underlying <interface>SimpleMessageListenerContainer</interface>
|
||||
is stopped, and before the AMQP connection is forced closed.
|
||||
If any workers are active when the shutdown signal comes
|
||||
they will be allowed to finish processing as long as they
|
||||
can finish within this timeout. Otherwise the connection is
|
||||
closed and messages remain unacked (if the channel is
|
||||
transactional). Defaults to 5000 milliseconds.
|
||||
<emphasis>Optional (Defaults to 5000)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-22-co" id="amqp-inbound-channel-adapter-xml-22">
|
||||
<para>By default, the underlying <interface>SimpleMessageListenerContainer</interface>
|
||||
uses a SimpleAsyncTaskExecutor implementation, that fires
|
||||
up a new Thread for each task, executing it asynchronously.
|
||||
By default, the number of concurrent threads is unlimited.
|
||||
|
||||
NOTE: This implementation does not reuse threads. Consider
|
||||
a thread-pooling TaskExecutor implementation as an alternative.
|
||||
<emphasis>Optional (Defaults to SimpleAsyncTaskExecutor)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-23-co" id="amqp-inbound-channel-adapter-xml-23">
|
||||
<para>By default the underlying <interface>SimpleMessageListenerContainer</interface>
|
||||
creates a new instance of the DefaultTransactionAttribute (takes
|
||||
the EJB approach to rolling back on runtime, but not checked
|
||||
exceptions.
|
||||
<emphasis>Optional (Defaults to DefaultTransactionAttribute)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-24-co" id="amqp-inbound-channel-adapter-xml-24">
|
||||
<para>Sets a Bean reference to an external
|
||||
<interface>PlatformTransactionManager</interface> on the
|
||||
underlying SimpleMessageListenerContainer. The transaction
|
||||
manager works in conjunction with the "channel-transacted"
|
||||
attribute.
|
||||
|
||||
If there is already a transaction in progress when the
|
||||
framework is sending or receiving a message, and the
|
||||
channelTransacted flag is true, then the commit or rollback
|
||||
of the messaging transaction will be deferred until the
|
||||
end of the current transaction. If the channelTransacted
|
||||
flag is false, then no transaction semantics apply to the
|
||||
messaging operation (it is auto-acked). For further information
|
||||
see chapter 1.9 of the Spring AMQP reference guide:
|
||||
|
||||
http://static.springsource.org/spring-amqp/docs/1.0.x/reference/html/#d0e525
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-channel-adapter-xml-25-co" id="amqp-inbound-channel-adapter-xml-25">
|
||||
<para>Tells the <interface>SimpleMessageListenerContainer</interface>
|
||||
how many messages to process in a single transaction (if
|
||||
the channel is transactional). For best results it should
|
||||
be less than or equal to the set "prefetch-count".
|
||||
<emphasis>Optional (Defaults to 1)</emphasis>.</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
<important>
|
||||
<para>Even though the Spring Integration JMS and AMQP support is very similar,
|
||||
important differences exist. The JMS Inbound Channel Adapter is using a
|
||||
JmsDestinationPollingSource under the covers and expects a configured Poller.
|
||||
|
||||
The AMQP Inbound Channel Adapter on the other side uses a
|
||||
<interface>SimpleMessageListenerContainer</interface> and is message
|
||||
driven. In that regard it is more similar to the JMS Message
|
||||
Driven Channel Adapter.</para>
|
||||
</important>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Outbound Channel Adapter</title>
|
||||
|
||||
<para>A configuration sample for an AMQP Outbound Channel Adapter is shown
|
||||
below with all available parameters.</para>
|
||||
<programlisting language="xml"><![CDATA[<int-amqp:outbound-channel-adapter id="outboundAmqp"]]><co id="amqp-outbound-channel-adapter-xml-1-co" linkends="amqp-outbound-channel-adapter-xml-1" /><![CDATA[
|
||||
channel="outboundChannel"]]><co id="amqp-outbound-channel-adapter-xml-2-co" linkends="amqp-outbound-channel-adapter-xml-2" /><![CDATA[
|
||||
amqp-template="myAmqpTemplate"]]><co id="amqp-outbound-channel-adapter-xml-3-co" linkends="amqp-outbound-channel-adapter-xml-3" /><![CDATA[
|
||||
exchange-name=""]]><co id="amqp-outbound-channel-adapter-xml-4-co" linkends="amqp-outbound-channel-adapter-xml-4" /><![CDATA[
|
||||
order="1"]]><co id="amqp-outbound-channel-adapter-xml-5-co" linkends="amqp-outbound-channel-adapter-xml-5" /><![CDATA[
|
||||
routing-key=""]]><co id="amqp-outbound-channel-adapter-xml-6-co" linkends="amqp-outbound-channel-adapter-xml-6" /><![CDATA[
|
||||
routing-key-expression=""]]><co id="amqp-outbound-channel-adapter-xml-7-co" linkends="amqp-outbound-channel-adapter-xml-7" /><![CDATA[/>]]>
|
||||
</programlisting>
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="amqp-outbound-channel-adapter-xml-1-co" id="amqp-outbound-channel-adapter-xml-1">
|
||||
<para>Unique ID for this adapter.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-channel-adapter-xml-2-co" id="amqp-outbound-channel-adapter-xml-2">
|
||||
<para>Message Channel to which Messages should be sent
|
||||
in order to have them converted and published to an
|
||||
AMQP Exchange.
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-channel-adapter-xml-3-co" id="amqp-outbound-channel-adapter-xml-3">
|
||||
<para>Bean Reference to the configured AMQP Template
|
||||
<emphasis>Optional (Defaults to "amqpTemplate")</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-channel-adapter-xml-4-co" id="amqp-outbound-channel-adapter-xml-4">
|
||||
<para>The name of the AMQP Exchange to which Messages
|
||||
should be sent. If not provided, Messages will be sent
|
||||
to the default, no-name Exchange.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-channel-adapter-xml-5-co" id="amqp-outbound-channel-adapter-xml-5">
|
||||
<para>The order for this consumer when multiple
|
||||
consumers are registered thereby enabling load-
|
||||
balancing and/or failover.
|
||||
<emphasis>Optional (Defaults to Ordered.LOWEST_PRECEDENCE [=Integer.MAX_VALUE])</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-channel-adapter-xml-6-co" id="amqp-outbound-channel-adapter-xml-6">
|
||||
<para>The fixed routing-key to use when sending Messages. By
|
||||
default, this will be an empty String.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-channel-adapter-xml-7-co" id="amqp-outbound-channel-adapter-xml-7">
|
||||
<para>The routing-key to use when sending Messages
|
||||
evaluated as an expression on the message (e.g.
|
||||
'payload.key'). By default, this will be an empty String.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Inbound Gateway</title>
|
||||
<para>A configuration sample for an AMQP Inbound Gateway is shown
|
||||
below with all available parameters.</para>
|
||||
<programlisting language="xml"><![CDATA[<int-amqp:inbound-gateway id="inboundGateway"]]><co id="amqp-inbound-gateway-adapter-xml-1-co" linkends="amqp-inbound-gateway-adapter-xml-1" /><![CDATA[
|
||||
request-channel="myRequestChannel"]]><co id="amqp-inbound-gateway-adapter-xml-2-co" linkends="amqp-inbound-gateway-adapter-xml-2" /><![CDATA[
|
||||
queue-names="si.test.queue"]]><co id="amqp-inbound-gateway-adapter-xml-3-co" linkends="amqp-inbound-gateway-adapter-xml-3" /><![CDATA[
|
||||
advice-chain=""]]><co id="amqp-inbound-gateway-adapter-xml-4-co" linkends="amqp-inbound-gateway-adapter-xml-4" /><![CDATA[
|
||||
concurrent-consumers="1"]]><co id="amqp-inbound-gateway-adapter-xml-5-co" linkends="amqp-inbound-gateway-adapter-xml-5" /><![CDATA[
|
||||
connection-factory="connectionFactory"]]><co id="amqp-inbound-gateway-adapter-xml-6-co" linkends="amqp-inbound-gateway-adapter-xml-6" /><![CDATA[
|
||||
reply-channel="myReplyChannel"]]><co id="amqp-inbound-gateway-adapter-xml-7-co" linkends="amqp-inbound-gateway-adapter-xml-7" /><![CDATA[/>]]>
|
||||
</programlisting>
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="amqp-inbound-gateway-adapter-xml-1-co" id="amqp-inbound-gateway-adapter-xml-1">
|
||||
<para>Unique ID for this adapter.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-gateway-adapter-xml-2-co" id="amqp-inbound-gateway-adapter-xml-2">
|
||||
<para>Message Channel to which converted Messages should be sent.
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-gateway-adapter-xml-3-co" id="amqp-inbound-gateway-adapter-xml-3">
|
||||
<para>Names of the AMQP Queues from which Messages should be consumed (comma-separated list).
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-gateway-adapter-xml-4-co" id="amqp-inbound-gateway-adapter-xml-4">
|
||||
<para>Extra AOP Advice(s) to handle cross cutting behavior associated with this Inbound Gateway.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-gateway-adapter-xml-5-co" id="amqp-inbound-gateway-adapter-xml-5">
|
||||
<para>Specify the number of concurrent consumers to
|
||||
create. Default is 1. Raising the number of concurrent
|
||||
consumers is recommended in order to scale the
|
||||
consumption of messages coming in from a queue.
|
||||
However, note that any ordering guarantees are lost
|
||||
once multiple consumers are registered. In general,
|
||||
stick with 1 consumer for low-volume queues.
|
||||
<emphasis>Optional (Defaults to 1)</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-gateway-adapter-xml-6-co" id="amqp-inbound-gateway-adapter-xml-6">
|
||||
<para>Bean reference to the RabbitMQ ConnectionFactory.
|
||||
<emphasis>Optional (Defaults to 'connectionFactory')</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-inbound-gateway-adapter-xml-7-co" id="amqp-inbound-gateway-adapter-xml-7">
|
||||
<para>Message Channel where reply Messages will be expected.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Outbound Gateway</title>
|
||||
<para>A configuration sample for an AMQP Outbound Gateway is shown
|
||||
below with all available parameters.</para>
|
||||
<programlisting language="xml"><![CDATA[<int-amqp:outbound-gateway id="inboundGateway"]]><co id="amqp-outbound-gateway-adapter-xml-1-co" linkends="amqp-outbound-gateway-adapter-xml-1" /><![CDATA[
|
||||
request-channel="myRequestChannel"]]><co id="amqp-outbound-gateway-adapter-xml-2-co" linkends="amqp-outbound-gateway-adapter-xml-2" /><![CDATA[
|
||||
amqp-template=""]]><co id="amqp-outbound-gateway-adapter-xml-3-co" linkends="amqp-outbound-gateway-adapter-xml-3" /><![CDATA[
|
||||
exchange-name=""]]><co id="amqp-outbound-gateway-adapter-xml-4-co" linkends="amqp-outbound-gateway-adapter-xml-4" /><![CDATA[
|
||||
order="1"]]><co id="amqp-outbound-gateway-adapter-xml-5-co" linkends="amqp-outbound-gateway-adapter-xml-5" /><![CDATA[
|
||||
reply-channel=""]]><co id="amqp-outbound-gateway-adapter-xml-6-co" linkends="amqp-outbound-gateway-adapter-xml-6" /><![CDATA[
|
||||
routing-key=""]]><co id="amqp-outbound-gateway-adapter-xml-7-co" linkends="amqp-outbound-gateway-adapter-xml-7" /><![CDATA[
|
||||
routing-key-expression=""]]><co id="amqp-outbound-gateway-adapter-xml-8-co" linkends="amqp-outbound-gateway-adapter-xml-8" /><![CDATA[/>]]>
|
||||
</programlisting>
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-1-co" id="amqp-outbound-gateway-adapter-xml-1">
|
||||
<para>Unique ID for this adapter.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-2-co" id="amqp-outbound-gateway-adapter-xml-2">
|
||||
<para>Message Channel to which Messages should be sent
|
||||
in order to have them converted and published to an
|
||||
AMQP Exchange.
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-3-co" id="amqp-outbound-gateway-adapter-xml-3">
|
||||
<para>Bean Reference to the configured AMQP Template
|
||||
<emphasis>Optional (Defaults to "amqpTemplate")</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-4-co" id="amqp-outbound-gateway-adapter-xml-4">
|
||||
<para>The name of the AMQP Exchange to which Messages should
|
||||
be sent. If not provided, Messages will be sent to the
|
||||
default, no-name Exchange.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-5-co" id="amqp-outbound-gateway-adapter-xml-5">
|
||||
<para>The order for this consumer when multiple
|
||||
consumers are registered thereby enabling load-
|
||||
balancing and/or failover.
|
||||
<emphasis>Optional (Defaults to Ordered.LOWEST_PRECEDENCE [=Integer.MAX_VALUE])</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-6-co" id="amqp-outbound-gateway-adapter-xml-6">
|
||||
<para>Message Channel to which replies should be sent after
|
||||
being received from an AQMP Queue and converted.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-7-co" id="amqp-outbound-gateway-adapter-xml-7">
|
||||
<para>The routing-key to use when sending Messages. By default,
|
||||
this will be an empty String.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="amqp-outbound-gateway-adapter-xml-8-co" id="amqp-outbound-gateway-adapter-xml-8">
|
||||
<para>The routing-key to use when sending Messages evealuated
|
||||
as an expression on the message (e.g. 'payload.key').
|
||||
By default, this will be an empty String.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>AMQP Backed Message Channels</title>
|
||||
|
||||
<para>
|
||||
There are two Message Channel implementations available. One is point-to-point, and the other is publish/subscribe.
|
||||
Both of these channels provide a wide range of configuration attributes for the underlying AmqpTemplate and
|
||||
SimpleMessageListenerContainer as you have seen on the Channel Adapters and Gateways. However, the examples we'll
|
||||
show here are going to have minimal configuration. Explore the XML schema to view the available attributes.
|
||||
</para>
|
||||
<para>
|
||||
A point-to-point channel would look like this:
|
||||
<programlisting language="xml"><![CDATA[<int-amqp:channel id="p2pChannel"/>]]></programlisting>
|
||||
Under the covers a Queue named "si.p2pChannel" would be declared, and this channel will send to
|
||||
that Queue (technically by sending to the no-name Direct Exchange with a routing key that matches this Queue's name).
|
||||
This channel will also register a consumer on that Queue. If for some reason, you want the Queue to be "pollable"
|
||||
instead of message-driven, then simply provide the "message-driven" flag with a value of false:
|
||||
<programlisting language="xml"><![CDATA[<int-amqp:channel id="p2pPollableChannel" message-driven="false"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
A publish/subscribe channel would look like this:
|
||||
<programlisting language="xml"><![CDATA[<int-amqp:publish-subscribe-channel id="pubSubChannel"/>]]></programlisting>
|
||||
Under the covers a Fanout Exchange named "si.fanout.pubSubChannel" would be declared, and this channel will send
|
||||
to that Fanout Exchange. This channel will also declare a server-named exclusive, autodelete, non-durable Queue
|
||||
and bind that to the Fanout Exchange while registering a consumer on that Queue to receive Messages. There is no
|
||||
"pollable" option for a publish-subscribe-channel; it must be message-driven.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>AMQP Samples</title>
|
||||
<para>
|
||||
To experiment with the AMQP adapters, check out the samples available in
|
||||
the Spring Integration Samples Git repository at:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem><ulink url="https://github.com/spring-integration-samples/basic/amqp">
|
||||
https://github.com/spring-integration-samples/basic/amqp</ulink>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
Currently there is one sample available that demonstrates the basic
|
||||
functionality of the Spring Integration AMQP Adapter using an Outbound Channel Adapter
|
||||
and an Inbound Channel Adapter. As AMQP Broker implementation the sample
|
||||
uses RabbitMQ (<ulink url="http://www.rabbitmq.com/">http://www.rabbitmq.com/</ulink>).
|
||||
</para>
|
||||
<note>
|
||||
In order to run the example you will need a running instance of RabbitMQ.
|
||||
A local installation with just the basic defaults will be sufficient.
|
||||
For detailed RabbitMQ installation procedures please visit:
|
||||
<ulink url="http://www.rabbitmq.com/install.html">
|
||||
http://www.rabbitmq.com/install.html
|
||||
</ulink>
|
||||
</note>
|
||||
<para>
|
||||
Once the sample application is started, you enter some text on the command prompt
|
||||
and a message containing that entered text is dispatched to the AMQP queue.
|
||||
In return that message is retrieved via Spring Integration and then printed
|
||||
to the console.
|
||||
</para>
|
||||
<para>
|
||||
The image belows illustrates the basic set of Spring Integration components
|
||||
used in this sample.
|
||||
</para>
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/spring-integration-amqp-sample-graph.png" format="PNG" align="center" scalefit="1" width="100%" contentdepth="100%"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/spring-integration-amqp-sample-graph.png" format="PNG" align="center" scalefit="1" width="100%" contentdepth="100%"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
<caption>The Spring Integration graph of the AMQP sample</caption>
|
||||
</section>
|
||||
</chapter>
|
||||
59
src/reference/docbook/bridge.xml
Normal file
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="bridge"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Messaging Bridge</title>
|
||||
|
||||
<section id="bridge-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
A Messaging Bridge is a relatively trivial endpoint that simply connects two Message Channels or Channel
|
||||
Adapters. For example, you may want to connect a <interfacename>PollableChannel</interfacename> to a
|
||||
<interfacename>SubscribableChannel</interfacename> so that the subscribing endpoints do not have to worry
|
||||
about any polling configuration. Instead, the Messaging Bridge provides the polling configuration.
|
||||
</para>
|
||||
<para>
|
||||
By providing an intermediary poller between two channels, a Messaging Bridge can be used to throttle inbound
|
||||
Messages. The poller's trigger will determine the rate at which messages arrive on the second channel, and the
|
||||
poller's "maxMessagesPerPoll" property will enforce a limit on the throughput.
|
||||
</para>
|
||||
<para>
|
||||
Another valid use for a Messaging Bridge is to connect two different systems. In such a scenario, Spring
|
||||
Integration's role would be limited to making the connection between these systems and managing a poller
|
||||
if necessary. It is probably more common to have at least a <emphasis>Transformer</emphasis> between the
|
||||
two systems to translate between their formats, and in that case, the channels would be provided as the
|
||||
'input-channel' and 'output-channel' of a Transformer endpoint. If data format translation is not required,
|
||||
the Messaging Bridge may indeed be sufficient.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="bridge-namespace">
|
||||
<title>Configuring Bridge</title>
|
||||
<para>
|
||||
The <bridge> element is used to create a Messaging Bridge between two Message Channels or Channel Adapters.
|
||||
Simply provide the "input-channel" and "output-channel" attributes:
|
||||
<programlisting language="xml"><![CDATA[ <int:bridge input-channel="input" output-channel="output"/>]]></programlisting>
|
||||
As mentioned above, a common use case for the Messaging Bridge is to connect a
|
||||
<interfacename>PollableChannel</interfacename> to a <interfacename>SubscribableChannel</interfacename>, and when
|
||||
performing this role, the Messaging Bridge may also serve as a throttler:
|
||||
<programlisting language="xml"><![CDATA[ <int:bridge input-channel="pollable" output-channel="subscribable">
|
||||
<int:poller max-messages-per-poll="10" fixed-rate="5000"/>
|
||||
</int:bridge>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Connecting Channel Adapters is just as easy. Here is a simple echo example between the "stdin" and "stdout"
|
||||
adapters from Spring Integration's "stream" namespace.
|
||||
<programlisting language="xml"><![CDATA[ <int-stream:stdin-channel-adapter id="stdin"/>
|
||||
|
||||
<int-stream:stdout-channel-adapter id="stdout"/>
|
||||
|
||||
<int:bridge id="echo" input-channel="stdin" output-channel="stdout"/>]]></programlisting>
|
||||
Of course, the configuration would be similar for other (potentially more useful) Channel Adapter bridges, such
|
||||
as File to JMS, or Mail to File. The various Channel Adapters will be discussed in upcoming chapters.
|
||||
</para>
|
||||
<note>
|
||||
<para>If no 'output-channel' is defined on a bridge, the reply channel provided by the inbound Message will
|
||||
be used, if available. If neither output or reply channel is available, an Exception will be thrown.</para>
|
||||
</note>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
123
src/reference/docbook/chain.xml
Normal file
@@ -0,0 +1,123 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="chain"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Handler Chain</title>
|
||||
|
||||
<section id="chain-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
The <classname>MessageHandlerChain</classname> is an implementation of
|
||||
<interfacename>MessageHandler</interfacename> that can be configured as a single Message Endpoint while
|
||||
actually delegating to a chain of other handlers, such as Filters, Transformers, Splitters, and so on.
|
||||
This can lead to a much simpler configuration when several handlers need to be connected in a fixed, linear
|
||||
progression. For example, it is fairly common to provide a Transformer before other components. Similarly, when
|
||||
providing a <emphasis>Filter</emphasis> before some other component in a chain, you are essentially creating a
|
||||
<ulink url="http://www.eaipatterns.com/MessageSelector.html">Selective Consumer</ulink>. In either case, the
|
||||
chain only requires a single <code>input-channel</code> and a single <code>output-channel</code> eliminating
|
||||
the need to define channels for each individual component.
|
||||
<tip>
|
||||
Spring Integration's <interfacename>Filter</interfacename> provides a boolean property <methodname>throwExceptionOnRejection</methodname>.
|
||||
When providing multiple Selective Consumers on the same point-to-point channel with different acceptance criteria,
|
||||
this value should be set to 'true' (the default is false) so that the dispatcher will know that the Message was
|
||||
rejected and as a result will attempt to pass the Message on to other subscribers. If the Exception were not
|
||||
thrown, then it would appear to the dispatcher as if the Message had been passed on successfully even though
|
||||
the Filter had <emphasis>dropped</emphasis> the Message to prevent further processing. If you do indeed want
|
||||
to "drop" the Messages, then the Filter's 'discard-channel' might be useful since it does give you a chance
|
||||
to perform some operation with the dropped message (e.g. send to a JMS queue or simply write to a log).
|
||||
</tip>
|
||||
</para>
|
||||
<para>
|
||||
The handler chain simplifies configuration while internally maintaining the same degree of loose coupling between
|
||||
components, and it is trivial to modify the configuration if at some point a non-linear arrangement is required.
|
||||
</para>
|
||||
<para>
|
||||
Internally, the chain will be expanded into a linear setup of the listed endpoints, separated by anonymous channels.
|
||||
The reply channel header will not be taken into account within the chain: only after the last handler is invoked
|
||||
will the resulting message be forwarded on to the reply channel or the chain's output channel. Because of this
|
||||
setup all handlers except the last required to implement the MessageProducer interface (which provides a
|
||||
'setOutputChannel()' method). The last handler only needs an output channel if the outputChannel on the
|
||||
MessageHandlerChain is set.
|
||||
<note>
|
||||
<para>
|
||||
As with other endpoints, the <code>output-channel</code> is optional. If there is a reply Message at the end of the
|
||||
chain, the output-channel takes precedence, but if not available, the chain handler will check for a
|
||||
reply channel header on the inbound Message as a fallback.
|
||||
</para>
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
In most cases there is no need to implement MessageHandlers yourself. The next section will focus on namespace
|
||||
support for the chain element. Most Spring Integration endpoints, like Service Activators and Transformers, are
|
||||
suitable for use within a <classname>MessageHandlerChain</classname>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="chain-namespace">
|
||||
<title>Configuring Chain</title>
|
||||
<para>
|
||||
The <chain> element provides an <code>input-channel</code> attribute, and if the last element in the chain is capable
|
||||
of producing reply messages (optional), it also supports an <code>output-channel</code> attribute. The sub-elements are then
|
||||
filters, transformers, splitters, and service-activators. The last element may also be a router.
|
||||
<programlisting language="xml"><![CDATA[ <int:chain input-channel="input" output-channel="output">
|
||||
<int:filter ref="someSelector" throw-exception-on-rejection="true"/>
|
||||
<int:header-enricher>
|
||||
<int:header name="foo" value="bar"/>
|
||||
</int:header-enricher>
|
||||
<int:service-activator ref="someService" method="someMethod"/>
|
||||
</int:chain>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The <header-enricher> element used in the above example will set a message header named "foo" with a value
|
||||
of "bar" on the message. A header enricher is a specialization of <interfacename>Transformer</interfacename>
|
||||
that touches only header values. You could obtain the same result by implementing a MessageHandler that did the
|
||||
header modifications and wiring that as a bean, but the header-enricher is obviously a simpler option.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Sometimes you need to make a nested call to another chain from within a chain and then come
|
||||
back and continue execution within the original chain.
|
||||
To accomplish this you can utilize a Messaging Gateway by including a <gateway> element.
|
||||
For example:
|
||||
<programlisting language="xml"><![CDATA[ <int:chain id="main-chain" input-channel="in" output-channel="out">
|
||||
<int:header-enricher>
|
||||
<int:header name="name" value="Many" />
|
||||
</int:header-enricher>
|
||||
<int:service-activator>
|
||||
<bean class="org.foo.SampleService" />
|
||||
</int:service-activator>
|
||||
<int:gateway request-channel="inputA"/>
|
||||
</int:chain>
|
||||
|
||||
<int:chain id="nested-chain-a" input-channel="inputA">
|
||||
<int:header-enricher>
|
||||
<int:header name="name" value="Moe" />
|
||||
</int:header-enricher>
|
||||
<int:gateway request-channel="inputB"/>
|
||||
<int:service-activator>
|
||||
<bean class="org.foo.SampleService" />
|
||||
</int:service-activator>
|
||||
</int:chain>
|
||||
|
||||
<int:chain id="nested-chain-b" input-channel="inputB">
|
||||
<int:header-enricher>
|
||||
<int:header name="name" value="Jack" />
|
||||
</int:header-enricher>
|
||||
<int:service-activator>
|
||||
<bean class="org.foo.SampleService" />
|
||||
</int:service-activator>
|
||||
</int:chain>]]></programlisting>
|
||||
|
||||
In the above example the <emphasis>nested-chain-a</emphasis> will be called at the end of
|
||||
<emphasis>main-chain</emphasis> processing by the 'gateway' element configured there. While in
|
||||
<emphasis>nested-chain-a</emphasis> a call to a <emphasis>nested-chain-b</emphasis> will be made
|
||||
after header enrichment and then it will come back to finish execution in <emphasis>nested-chain-b</emphasis>.
|
||||
Finally the flow returns to the <emphasis>main-chain</emphasis>. When the nested version of a <gateway>
|
||||
element is defined in the chain, it does not require the <code>service-interface</code> attribute.
|
||||
Instead, it simple takes the message in its current state and places it on the channel defined via
|
||||
the <code>request-channel</code> attribute. When the downstream flow initiated by that gateway completes,
|
||||
a <interfacename>Message</interfacename> will be returned to the gateway and continue its journey within
|
||||
the current chain.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
247
src/reference/docbook/changes-1.0-2.0.xml
Normal file
@@ -0,0 +1,247 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="migration-1.0-2.0"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Changes between 1.0 and 2.0</title>
|
||||
|
||||
<para>
|
||||
For a detailed migration guide in regards to upgrading an existing application
|
||||
that uses Spring Integration older than version 2.0, please see:
|
||||
</para>
|
||||
<para>
|
||||
<ulink url="http://www.springsource.org/node/2976"/>
|
||||
</para>
|
||||
<section id="migration-spring-30-support">
|
||||
<title>Spring 3 support</title>
|
||||
<para>
|
||||
Spring Integration 2.0 is built on top of Spring 3.0.5 and makes many of its features available to our users.
|
||||
</para>
|
||||
|
||||
<section id="spel-support">
|
||||
<title>Support for the Spring Expression Language (SpEL)</title>
|
||||
<para>
|
||||
You can now use SpEL expressions within the <emphasis>transformer, router, filter,
|
||||
splitter, aggregator, service-activator, header-enricher</emphasis>, and many more elements of the
|
||||
Spring Integration core namespace as well as various adapters.
|
||||
There are many samples provided throughout this manual.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="conversion-support">
|
||||
<title>ConversionService and Converter</title>
|
||||
<para>
|
||||
You can now benefit from <emphasis>Conversion Service</emphasis> support provided with Spring while configuring
|
||||
many Spring Integration components such as <ulink url="http://www.eaipatterns.com/DatatypeChannel.html">Datatype Channel</ulink>.
|
||||
See <xref linkend="channel-implementations"/> as well <xref linkend="service-activator-introduction"/>.
|
||||
Also, the SpEL support mentioned in the previous point also relies upon the ConversionService. Therefore, you
|
||||
can register Converters once, and take advantage of them anywhere you are using SpEL expressions.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="task-scheduler-poller-support">
|
||||
<title>TaskScheduler and Trigger</title>
|
||||
<para>
|
||||
Spring 3.0 defines two new strategies related to scheduling: <emphasis>TaskScheduler and Trigger</emphasis>
|
||||
Spring Integration (which uses a lot of scheduling) now builds upon these. In fact, Spring Integration 1.0
|
||||
had originally defined some of the components (e.g. CronTrigger) that have now been migrated into Spring 3.0's
|
||||
core API. Now, you can benefit from reusing the same components within the entire Application Context (not just
|
||||
Spring Integration configuration). Configuration of Spring Integration Pollers has been greatly simplified
|
||||
as well by providing attributes for directly configuring rates, delays, cron expressions, and trigger references.
|
||||
See <xref linkend="channel-adapter"/> for sample configurations.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="rest-support">
|
||||
<title>RestTemplate and HttpMessageConverter</title>
|
||||
<para>
|
||||
Our outbound HTTP adapters now delegate to Spring's RestTemplate for executing the HTTP request and handling its response.
|
||||
This also means that you can reuse any custom HttpMessageConverter implementations.
|
||||
See <xref linkend="http-outbound"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="new-eip">
|
||||
<title>Enterprise Integration Pattern Additions</title>
|
||||
<para>
|
||||
Also in 2.0 we have added support for even more of the patterns described in Hohpe and Woolf's
|
||||
<ulink url="http://www.eaipatterns.com/">Enterprise Integration Patterns</ulink> book.
|
||||
</para>
|
||||
|
||||
<section id="new-message-history">
|
||||
<title>Message History</title>
|
||||
<para>
|
||||
We now provide support for the <ulink url="http://www.eaipatterns.com/MessageHistory.html">Message History</ulink> pattern
|
||||
allowing you to keep track of all traversed components, including the name of each channel and endpoint as well as the timestamp
|
||||
of that traversal. See <xref linkend="message-history"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-message-store">
|
||||
<title>Message Store</title>
|
||||
<para>
|
||||
We now provide support for the <ulink url="http://www.eaipatterns.com/MessageStore.html">Message Store</ulink> pattern.
|
||||
The Message Store provides a strategy for persisting messages on behalf of any process whose scope extends beyond a single
|
||||
transaction, such as the Aggregator and Resequencer. Many sections of this document provide samples on how to use a Message Store as it
|
||||
affects several areas of Spring Integration. See <xref linkend="message-store"/>, <xref linkend="claim-check"/>,
|
||||
<xref linkend="channel"/>, <xref linkend="aggregator"/>, <xref linkend="jdbc"/>, and <xref linkend="resequencer"/> for more details
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-claim-check">
|
||||
<title>Claim Check</title>
|
||||
<para>
|
||||
We have added an implementation of the <ulink url="http://www.eaipatterns.com/StoreInLibrary.html">Claim Check</ulink> pattern.
|
||||
The idea behind the Claim Check pattern is that you can exchange a Message payload for a "claim ticket" and vice-versa.
|
||||
This allows you to reduce bandwidth and/or avoid potential security issues when sending Messages across channels.
|
||||
See <xref linkend="claim-check"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-control-bus">
|
||||
<title>Control Bus</title>
|
||||
<para>
|
||||
We have provided implementations of the <ulink url="http://www.eaipatterns.com/ControlBus.html">Control Bus</ulink> pattern which
|
||||
allows you to use messaging to manage and monitor endpoints and channels. The implementations include both a SpEL-based approach
|
||||
and one that executes Groovy scripts.
|
||||
See <xref linkend="control-bus"/> and <xref linkend="groovy-control-bus"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="new-adapters">
|
||||
<title>New Channel Adapters and Gateways</title>
|
||||
<para>
|
||||
We have added several new Channel Adapters and Messaging Gateways in Spring Integration 2.0.
|
||||
</para>
|
||||
|
||||
|
||||
<section id="new-ip">
|
||||
<title>TCP/UDP Adapters</title>
|
||||
<para>
|
||||
We have added Channel Adapters for receiving and sending messages over the TCP and UDP internet protocols.
|
||||
See <xref linkend="ip"/> for more details. Also, you can checkout the following blog:
|
||||
<ulink url="http://blog.springsource.com/2010/03/29/using-udp-and-tcp-adapters-in-spring-integration-2-0-m3/">TCP/UDP support</ulink>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-twitter">
|
||||
<title>Twitter Adapters</title>
|
||||
<para>
|
||||
Twitter adapters provides support for sending and receiving Twitter Status
|
||||
updates as well as Direct Messages. You can also perform Twitter Searches with an inbound Channel Adapter.
|
||||
See <xref linkend="twitter"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-xmpp">
|
||||
<title>XMPP Adapters</title>
|
||||
<para>
|
||||
The new XMPP adapters support both Chat Messages and Presence events. See <xref linkend="xmpp"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-ftp">
|
||||
<title>FTP/FTPS Adapters</title>
|
||||
<para>
|
||||
Inbound and outbound File transfer support over FTP/FTPS is now available. See <xref linkend="ftp"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-sftp">
|
||||
<title>SFTP Adapters</title>
|
||||
<para>
|
||||
Inbound and outbound File transfer support over SFTP is now available. See <xref linkend="sftp"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-feed">
|
||||
<title>Feed Adapters</title>
|
||||
<para>
|
||||
We have also added Channel Adapters for receiving news feeds (ATOM/RSS). See <xref linkend="feed"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="new-other">
|
||||
<title>Other Additions</title>
|
||||
|
||||
<section id="new-groovy">
|
||||
<title>Groovy Support</title>
|
||||
<para>
|
||||
With Spring Integration 2.0 we've added Groovy support allowing you to
|
||||
use Groovy scripting language to provide integration and/or business logic.
|
||||
See <xref linkend="groovy"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-map-transformer">
|
||||
<title>Map Transformers</title>
|
||||
<para>
|
||||
These symmetrical transformers convert payload objects to and from a Map. See <xref linkend="transformer"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-json-transformer">
|
||||
<title>JSON Transformers</title>
|
||||
<para>
|
||||
These symmetrical transformers convert payload objects to and from JSON. See <xref linkend="transformer"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-serialize-transformer">
|
||||
<title>Serialization Transformers</title>
|
||||
<para>
|
||||
These symmetrical transformers convert payload objects to and from byte arrays.
|
||||
They also support the Serializer and Deserializer strategy interfaces that have been added as of Spring 3.0.5.
|
||||
See <xref linkend="transformer"/> for more details.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="new-refactoring">
|
||||
<title>Framework Refactoring</title>
|
||||
<para>
|
||||
The core API went through some significant refactoring to make it simpler and more usable. Although we anticipate
|
||||
that the impact to the end user should be minimal, please read through this document to find what was
|
||||
changed. Especially, visit <xref linkend="dynamic-routers"/> , <xref linkend="gateway"/>, <xref linkend="http-outbound"/>,
|
||||
<xref linkend="message"/>, and <xref linkend="aggregator"/> for more details. If you are depending directly on some of
|
||||
the core components (Message, MessageHeaders, MessageChannel, MessageBuilder, etc.), you will notice that you need to
|
||||
update any import statements. We restructured some packaging to provide the flexibility we needed for extending the
|
||||
domain model while avoiding any cyclical dependencies (it is a policy of the framework to avoid such "tangles").
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-infrastructure">
|
||||
<title>New Source Control Management and Build Infrastructure</title>
|
||||
<para>
|
||||
With Spring Integration 2.0 we have switched our build environment to use Git for source control. To access our repository simply follow this URL:
|
||||
<ulink url="http://git.springsource.org/spring-integration">http://git.springsource.org/spring-integration</ulink>.
|
||||
We have also switched our build system to <ulink url="http://gradle.org/">Gradle</ulink>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-samples">
|
||||
<title>New Spring Integration Samples</title>
|
||||
<para>
|
||||
With Spring Integration 2.0 we have decoupled the samples from our main release distribution. Please read this blog to get more info
|
||||
<ulink url="http://blog.springsource.com/2010/09/29/new-spring-integration-samples/">New Spring Integration Samples</ulink>
|
||||
We have also created many new samples, including samples for every new Adapter.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="new-sts">
|
||||
<title>SpringSource Tool Suite Visual Editor for Spring Integration</title>
|
||||
<para>
|
||||
There is an amazing new visual editor for Spring Integration included within the latest version of SpringSource Tool Suite.
|
||||
If you are not already using STS, please download it here:
|
||||
</para>
|
||||
<para>
|
||||
<ulink url="http://www.springsource.com/landing/best-development-tool-enterprise-java"/>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
|
||||
9
src/reference/docbook/changes-2.0-2.1.xml
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="migration-2.0-2.1"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Changes between 2.0 and 2.1</title>
|
||||
<para>
|
||||
For an overview of the changes in Spring Integration 2.1 since version 2.0,
|
||||
please see <xref linkend="whats-new"/>.
|
||||
</para>
|
||||
</section>
|
||||
135
src/reference/docbook/channel-adapter.xml
Normal file
@@ -0,0 +1,135 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="channel-adapter"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Channel Adapter</title>
|
||||
<para>
|
||||
A Channel Adapter is a Message Endpoint that enables connecting a single sender or receiver to a Message Channel.
|
||||
Spring Integration provides a number of adapters out of the box to support various transports, such as JMS, File,
|
||||
HTTP, Web Services, Mail, and more. Those will be discussed in upcoming chapters of this reference guide. However, this
|
||||
chapter focuses on the simple but flexible Method-invoking Channel Adapter support. There are both inbound and
|
||||
outbound adapters, and each may be configured with XML elements provided in the core namespace. These provide an
|
||||
easy way to extend Spring Integration as long as you have a method that can be invoked as either a source or
|
||||
destination.
|
||||
</para>
|
||||
|
||||
<section id="channel-adapter-namespace-inbound">
|
||||
<title>Configuring Inbound Channel Adapter</title>
|
||||
<para>
|
||||
An "inbound-channel-adapter" element can invoke any method on a Spring-managed Object and send a non-null return
|
||||
value to a <interfacename>MessageChannel</interfacename> after converting it to a <classname>Message</classname>.
|
||||
When the adapter's subscription is activated, a poller will attempt to receive messages from the source. The
|
||||
poller will be scheduled with the <interfacename>TaskScheduler</interfacename> according to the provided
|
||||
configuration. To configure the polling interval or cron expression for an individual channel-adapter,
|
||||
provide a 'poller' element with one of the scheduling attributes, such as 'fixed-rate' or 'cron'.
|
||||
<programlisting language="xml"><![CDATA[<int:inbound-channel-adapter ref="source1" method="method1" channel="channel1">
|
||||
<int:poller fixed-rate="5000"/>
|
||||
</int:inbound-channel-adapter>
|
||||
|
||||
<int:inbound-channel-adapter ref="source2" method="method2" channel="channel2">
|
||||
<int:poller cron="30 * 9-17 * * MON-FRI"/>
|
||||
</int:channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
If no poller is provided, then a single default poller must be registered within the context.
|
||||
See <xref linkend="endpoint-namespace"/> for more detail.
|
||||
</para>
|
||||
</note>
|
||||
<important>
|
||||
<para><emphasis>Poller Configuration</emphasis> </para>
|
||||
<para>
|
||||
Some <code>inbound-channel-adapter</code> types are backed by a <classname>SourcePollingChannelAdapter</classname> which
|
||||
means they contain Poller configuration which will poll the <classname>MessageSource</classname> (invoke a custom method
|
||||
which produces the value that becomes a <classname>Message</classname> payload) based on the configuration
|
||||
specified in the Poller.
|
||||
</para>
|
||||
<para>For example:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:poller max-messages-per-poll="1" fixed-rate="1000"/>
|
||||
|
||||
<int:poller max-messages-per-poll="10" fixed-rate="1000"/>]]></programlisting>
|
||||
In the the first configuration the polling task will be invoked once per poll and during such task (poll)
|
||||
the method (which results in the production of the Message) will be invoked once based on the
|
||||
<code>max-messages-per-poll</code> attribute value. In the second configuration the polling task will be invoked
|
||||
10 times per poll or until it returns 'null' thus possibly producing 10 Messages per poll while each poll happens
|
||||
at 1 second intervals.
|
||||
However what if the configuration looks like this:
|
||||
<programlisting language="xml"><![CDATA[<int:poller fixed-rate="1000"/>]]></programlisting>
|
||||
Note there is no <code>max-messages-per-poll</code> specified. As you'll learn later the identical poller configuration
|
||||
in the <classname>PollingConsumer</classname> (e.g., service-activator, filter, router etc.) would have a default
|
||||
value of -1 for <code>max-messages-per-poll</code> which means "execute poling task non-stop unless polling method
|
||||
returns null (e.g., no more Messages in the QueueChannel)" and then sleep for 1 second.
|
||||
</para>
|
||||
<para>
|
||||
However in the SourcePollingChannelAdapter it is a bit different.
|
||||
The default value for <code>max-messages-per-poll</code> will be set to 1 by default unless you explicitly set it to
|
||||
a negative value (e.g., -1). It is done so to make sure that poller can react to a LifeCycle events (e.g., start/stop)
|
||||
and prevent it from potentially spinning in the infinite loop if the implementation of the custom
|
||||
method of the <classname>MessageSource</classname> has a potential to never return null and happened to be non-interruptible.
|
||||
</para>
|
||||
<para>
|
||||
However if you are sure that your method can return null and you need the behavior where you want to poll
|
||||
for as many sources as available per each poll, then you should explicitly set <code>max-messages-per-poll</code>
|
||||
to negative value.
|
||||
<programlisting language="xml"><![CDATA[<int:poller max-messages-per-poll="-1" fixed-rate="1000"/>]]></programlisting>
|
||||
|
||||
</para>
|
||||
|
||||
</important>
|
||||
</section>
|
||||
|
||||
<section id="channel-adapter-namespace-outbound">
|
||||
<title>Configuring Outbound Channel Adapter</title>
|
||||
<para>
|
||||
An "outbound-channel-adapter" element can also connect a <interfacename>MessageChannel</interfacename> to any POJO consumer
|
||||
method that should be invoked with the payload of Messages sent to that channel.
|
||||
<programlisting language="xml"><![CDATA[<int:outbound-channel-adapter channel="channel1" ref="target" method="handle"/>
|
||||
|
||||
<beans:bean id="target" class="org.Foo"/>]]>
|
||||
</programlisting>
|
||||
|
||||
If the channel being adapted is a <interfacename>PollableChannel</interfacename>, provide a poller sub-element:
|
||||
<programlisting language="xml"><![CDATA[<int:outbound-channel-adapter channel="channel2" ref="target" method="handle">
|
||||
]]><emphasis><![CDATA[<int:poller fixed-rate="3000"/>
|
||||
]]></emphasis><![CDATA[
|
||||
</int:outbound-channel-adapter>
|
||||
|
||||
<beans:bean id="target" class="org.Foo"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Using a "ref" attribute is generally recommended if the POJO consumer implementation can be reused
|
||||
in other <code><outbound-channel-adapter></code> definitions. However if the consumer implementation
|
||||
is only referenced by a single definition of the <code><outbound-channel-adapter></code>, you
|
||||
can define it as inner bean:
|
||||
<programlisting language="xml"><![CDATA[<int:outbound-channel-adapter channel="channel" method="handle">
|
||||
<beans:bean class="org.Foo"/>
|
||||
]]><![CDATA[
|
||||
</int:outbound-channel-adapter>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
Using both the "ref" attribute and an inner handler definition in the same <code><outbound-channel-adapter></code>
|
||||
configuration is not allowed as it creates an ambiguous condition. Such a configuration will result in an Exception
|
||||
being thrown.
|
||||
</para>
|
||||
</note>
|
||||
<para>
|
||||
Any Channel Adapter can be created without a "channel" reference in which case it will implicitly create an
|
||||
instance of <classname>DirectChannel</classname>. The created channel's name will match the "id" attribute
|
||||
of the <code><inbound-channel-adapter></code> or <code><outbound-channel-adapter></code> element. Therefore, if the "channel"
|
||||
is not provided, the "id" is required.
|
||||
</para>
|
||||
<para>
|
||||
Like many other Spring Integration components, the <code><inbound-channel-adapter></code> and
|
||||
<code><outbound-channel-adapter></code> also provide support for SpEL expression evaluation. To use SpEL, provide the
|
||||
expression string via the 'expression' attribute instead of providing the 'ref' and 'method' attributes that are used for
|
||||
method-invocation on a bean. When an Expression is evaluated, it follows the same contract as method-invocation where:
|
||||
the <emphasis>expression</emphasis> for an <code><inbound-channel-adapter></code> will generate a message anytime the
|
||||
evaluation result is a <emphasis>non-null</emphasis> value, while the <emphasis>expression</emphasis> for an
|
||||
<code><outbound-channel-adapter></code> must be the equivalent of a <emphasis>void</emphasis> returning method invocation.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
807
src/reference/docbook/channel.xml
Normal file
@@ -0,0 +1,807 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="channel"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Channels</title>
|
||||
<para>
|
||||
While the <interfacename>Message</interfacename> plays the crucial role of encapsulating data, it is the
|
||||
<interfacename>MessageChannel</interfacename> that decouples message producers from message consumers.
|
||||
</para>
|
||||
|
||||
<section id="channel-interfaces">
|
||||
<title>The MessageChannel Interface</title>
|
||||
<para>
|
||||
Spring Integration's top-level <interfacename>MessageChannel</interfacename> interface is defined as follows.
|
||||
<programlisting language="java"><![CDATA[public interface MessageChannel {
|
||||
|
||||
boolean send(Message message);
|
||||
|
||||
boolean send(Message message, long timeout);
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
When sending a message, the return value will be <emphasis>true</emphasis> if the message is sent successfully.
|
||||
If the send call times out or is interrupted, then it will return <emphasis>false</emphasis>.
|
||||
</para>
|
||||
|
||||
<section id="channel-interfaces-pollablechannel">
|
||||
<title>PollableChannel</title>
|
||||
<para>
|
||||
Since Message Channels may or may not buffer Messages (as discussed in the overview), there are two
|
||||
sub-interfaces defining the buffering (pollable) and non-buffering (subscribable) channel behavior. Here is the
|
||||
definition of <interfacename>PollableChannel</interfacename>.
|
||||
<programlisting language="java">public interface PollableChannel extends MessageChannel {
|
||||
|
||||
Message<?> receive();
|
||||
|
||||
Message<?> receive(long timeout);
|
||||
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Similar to the send methods, when receiving a message, the return value will be <emphasis>null</emphasis> in the
|
||||
case of a timeout or interrupt.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="channel-interfaces-subscribablechannel">
|
||||
<title>SubscribableChannel</title>
|
||||
<para>
|
||||
The <interfacename>SubscribableChannel</interfacename> base interface is implemented by channels that send
|
||||
Messages directly to their subscribed <interfacename>MessageHandler</interfacename>s. Therefore, they do not
|
||||
provide receive methods for polling, but instead define methods for managing those subscribers:
|
||||
<programlisting language="java">public interface SubscribableChannel extends MessageChannel {
|
||||
|
||||
boolean subscribe(MessageHandler handler);
|
||||
|
||||
boolean unsubscribe(MessageHandler handler);
|
||||
|
||||
}</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="channel-implementations">
|
||||
<title>Message Channel Implementations</title>
|
||||
<para>
|
||||
Spring Integration provides several different Message Channel implementations. Each is briefly described in the
|
||||
sections below.
|
||||
</para>
|
||||
<section id="channel-implementations-publishsubscribechannel">
|
||||
<title>PublishSubscribeChannel</title>
|
||||
<para>
|
||||
The <classname>PublishSubscribeChannel</classname> implementation broadcasts any Message
|
||||
sent to it to all of its subscribed handlers. This is most often used for sending
|
||||
<emphasis>Event Messages</emphasis> whose primary role is notification as opposed to
|
||||
<emphasis>Document Messages</emphasis> which are generally intended to be processed by
|
||||
a single handler. Note that the <classname>PublishSubscribeChannel</classname> is
|
||||
intended for sending only. Since it broadcasts to its subscribers directly when its
|
||||
<methodname>send(Message)</methodname> method is invoked, consumers cannot poll for
|
||||
Messages (it does not implement <interfacename>PollableChannel</interfacename> and
|
||||
therefore has no <methodname>receive()</methodname> method). Instead, any subscriber
|
||||
must be a <interfacename>MessageHandler</interfacename> itself, and the subscriber's
|
||||
<methodname>handleMessage(Message)</methodname> method will be invoked in turn.
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-implementations-queuechannel">
|
||||
<title>QueueChannel</title>
|
||||
<para>
|
||||
The <classname>QueueChannel</classname> implementation wraps a queue. Unlike the
|
||||
<classname>PublishSubscribeChannel</classname>, the <classname>QueueChannel</classname> has point-to-point
|
||||
semantics. In other words, even if the channel has multiple consumers, only one of them should receive any
|
||||
Message sent to that channel. It provides a default no-argument constructor (providing an essentially unbounded
|
||||
capacity of <code>Integer.MAX_VALUE</code>) as well as a constructor that accepts the queue capacity:
|
||||
<programlisting language="java">public QueueChannel(int capacity)</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
A channel that has not reached its capacity limit will store messages in its internal queue, and the
|
||||
<methodname>send()</methodname> method will return immediately even if no receiver is ready to handle the
|
||||
message. If the queue has reached capacity, then the sender will block until room is available. Or, if using
|
||||
the send call that accepts a timeout, it will block until either room is available or the timeout period
|
||||
elapses, whichever occurs first. Likewise, a receive call will return immediately if a message is available
|
||||
on the queue, but if the queue is empty, then a receive call may block until either a message is available
|
||||
or the timeout elapses. In either case, it is possible to force an immediate return regardless of the
|
||||
queue's state by passing a timeout value of 0. Note however, that calls to the no-arg versions of
|
||||
<methodname>send()</methodname> and <methodname>receive()</methodname> will block indefinitely.
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-implementations-prioritychannel">
|
||||
<title>PriorityChannel</title>
|
||||
<para>
|
||||
Whereas the <classname>QueueChannel</classname> enforces first-in/first-out (FIFO) ordering, the
|
||||
<classname>PriorityChannel</classname> is an alternative implementation that allows for messages
|
||||
to be ordered within the channel based upon a priority. By default the priority is determined by the
|
||||
'<literal>priority</literal>' header within each message. However, for custom priority determination
|
||||
logic, a comparator of type <classname>Comparator<Message<?>></classname> can be provided
|
||||
to the <classname>PriorityChannel</classname>'s constructor.
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-implementations-rendezvouschannel">
|
||||
<title>RendezvousChannel</title>
|
||||
<para>
|
||||
The <classname>RendezvousChannel</classname> enables a "direct-handoff" scenario where a sender will block
|
||||
until another party invokes the channel's <methodname>receive()</methodname> method or vice-versa. Internally,
|
||||
this implementation is quite similar to the <classname>QueueChannel</classname> except that it uses a
|
||||
<classname>SynchronousQueue</classname> (a zero-capacity implementation of
|
||||
<interfacename>BlockingQueue</interfacename>). This works well in situations where the sender and receiver are
|
||||
operating in different threads but simply dropping the message in a queue asynchronously is not appropriate.
|
||||
In other words, with a <classname>RendezvousChannel</classname> at least the sender knows that some receiver
|
||||
has accepted the message, whereas with a <classname>QueueChannel</classname>, the message would have been
|
||||
stored to the internal queue and potentially never received.
|
||||
</para>
|
||||
<tip>
|
||||
<para>
|
||||
Keep in mind that all of these queue-based channels are storing messages in-memory only by default.
|
||||
When persistence is required, you can either provide a 'message-store' attribute within the 'queue'
|
||||
element to reference a persistent MessageStore implementation, or you can replace the local channel
|
||||
with one that is backed by a persistent broker, such as a JMS-backed channel or Channel Adapter.
|
||||
The latter option allows you to take advantage of any JMS provider's
|
||||
implementation for message persistence, and it will be discussed in <xref linkend="jms"/>. However, when
|
||||
buffering in a queue is not necessary, the simplest approach is to rely upon the
|
||||
<classname>DirectChannel</classname> discussed next.
|
||||
</para>
|
||||
</tip>
|
||||
<para>
|
||||
The <classname>RendezvousChannel</classname> is also useful for implementing request-reply
|
||||
operations. The sender can create a temporary, anonymous instance of <classname>RendezvousChannel</classname>
|
||||
which it then sets as the 'replyChannel' header when building a Message. After sending that Message, the sender
|
||||
can immediately call receive (optionally providing a timeout value) in order to block while waiting for a reply
|
||||
Message. This is very similar to the implementation used internally by many of Spring Integration's
|
||||
request-reply components.
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-implementations-directchannel">
|
||||
<title>DirectChannel</title>
|
||||
<para>
|
||||
The <classname>DirectChannel</classname> has point-to-point semantics but otherwise is more similar to the
|
||||
<classname>PublishSubscribeChannel</classname> than any of the queue-based channel implementations described
|
||||
above. It implements the <interfacename>SubscribableChannel</interfacename> interface instead of the
|
||||
<interfacename>PollableChannel</interfacename> interface, so it dispatches Messages directly to a subscriber.
|
||||
As a point-to-point channel, however, it differs from the <classname>PublishSubscribeChannel</classname> in
|
||||
that it will only send each Message to a <emphasis>single</emphasis> subscribed
|
||||
<classname>MessageHandler</classname>.
|
||||
</para>
|
||||
<para>
|
||||
In addition to being the simplest point-to-point channel option, one of its most important features is that
|
||||
it enables a single thread to perform the operations on "both sides" of the channel. For example, if a handler
|
||||
is subscribed to a <classname>DirectChannel</classname>, then sending a Message to that channel will trigger
|
||||
invocation of that handler's <methodname>handleMessage(Message)</methodname> method <emphasis>directly in the
|
||||
sender's thread</emphasis>, before the send() method invocation can return.
|
||||
</para>
|
||||
<para>
|
||||
The key motivation for providing a channel implementation with this behavior is to support transactions that
|
||||
must span across the channel while still benefiting from the abstraction and loose coupling that the channel
|
||||
provides. If the send call is invoked within the scope of a transaction, then the outcome of the handler's
|
||||
invocation (e.g. updating a database record) will play a role in determining the ultimate result of that
|
||||
transaction (commit or rollback).
|
||||
<note>
|
||||
Since the <classname>DirectChannel</classname> is the simplest option and does not add any additional
|
||||
overhead that would be required for scheduling and managing the threads of a poller, it is the default
|
||||
channel type within Spring Integration. The general idea is to define the channels for an application and
|
||||
then to consider which of those need to provide buffering or to throttle input, and then modify those to
|
||||
be queue-based <interfacename>PollableChannels</interfacename>. Likewise, if a channel needs to broadcast
|
||||
messages, it should not be a <classname>DirectChannel</classname> but rather a
|
||||
<classname>PublishSubscribeChannel</classname>. Below you will see how each of these can be configured.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
The <classname>DirectChannel</classname> internally delegates to a Message Dispatcher to invoke its
|
||||
subscribed Message Handlers, and that dispatcher can have a load-balancing strategy. The load-balancer
|
||||
determines how invocations will be ordered in the case that there are multiple handlers subscribed to the
|
||||
same channel. When using the namespace support described below, the default strategy is
|
||||
"round-robin" which essentially load-balances across the handlers in rotation.
|
||||
<note>
|
||||
The "round-robin" strategy is currently the only implementation available out-of-the-box in Spring
|
||||
Integration. Other strategy implementations may be added in future versions.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
The load-balancer also works in combination with a boolean <emphasis>failover</emphasis> property.
|
||||
If the "failover" value is true (the default), then the dispatcher will fall back to any subsequent
|
||||
handlers as necessary when preceding handlers throw Exceptions. The order is determined by an optional
|
||||
order value defined on the handlers themselves or, if no such value exists, the order in which the
|
||||
handlers are subscribed.
|
||||
</para>
|
||||
<para>
|
||||
If a certain situation requires that the dispatcher always try to invoke the first handler, then
|
||||
fallback in the same fixed order sequence every time an error occurs, no load-balancing strategy should
|
||||
be provided. In other words, the dispatcher still supports the failover boolean property even when no
|
||||
load-balancing is enabled. Without load-balancing, however, the invocation of handlers will always begin
|
||||
with the first according to their order. For example, this approach works well when there is a clear
|
||||
definition of primary, secondary, tertiary, and so on. When using the namespace support, the "order"
|
||||
attribute on any endpoint will determine that order.
|
||||
</para>
|
||||
<note>
|
||||
Keep in mind that load-balancing and failover only apply when a channel has more than one
|
||||
subscribed Message Handler. When using the namespace support, this means that more than one
|
||||
endpoint shares the same channel reference in the "input-channel" attribute.
|
||||
</note>
|
||||
</section>
|
||||
<section id="executor-channel">
|
||||
<title>ExecutorChannel</title>
|
||||
<para>
|
||||
The <classname>ExecutorChannel</classname> is a point-to-point channel that supports
|
||||
the same dispatcher configuration as <classname>DirectChannel</classname> (load-balancing strategy
|
||||
and the failover boolean property). The key difference between these two dispatching channel types
|
||||
is that the <classname>ExecutorChannel</classname> delegates to an instance of
|
||||
<interfacename>TaskExecutor</interfacename> to perform the dispatch. This means that the send method
|
||||
typically will not block, but it also means that the handler invocation may not occur in the sender's
|
||||
thread. It therefore <emphasis>does not support transactions spanning the sender and receiving
|
||||
handler</emphasis>.
|
||||
<tip>
|
||||
Note that there are occasions where the sender may block. For example, when using a
|
||||
TaskExecutor with a rejection-policy that throttles back on the client (such as the
|
||||
<code>ThreadPoolExecutor.CallerRunsPolicy</code>), the sender's thread will execute
|
||||
the method directly anytime the thread pool is at its maximum capacity and the
|
||||
executor's work queue is full. Since that situation would only occur in a non-predictable
|
||||
way, that obviously cannot be relied upon for transactions.
|
||||
</tip>
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-implementations-threadlocalchannel">
|
||||
<title>Scoped Channel</title>
|
||||
<para>
|
||||
Spring Integration 1.0 provided a <classname>ThreadLocalChannel</classname> implementation, but that has been removed as of 2.0. Now, there is a more general way for handling the same requirement by simply adding a "scope" attribute to a channel. The value of the attribute can be any name of a Scope that is available within the context. For example, in a web environment, certain Scopes are available, and any custom Scope implementations can be registered with the context. Here's an example of a ThreadLocal-based scope being applied to a channel, including the registration of the Scope itself.</para>
|
||||
<programlisting language="xml"><![CDATA[ <int:channel id="threadScopedChannel" scope="thread">
|
||||
<int:queue />
|
||||
</int:channel>
|
||||
|
||||
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
|
||||
<property name="scopes">
|
||||
<map>
|
||||
<entry key="thread" value="org.springframework.context.support.SimpleThreadScope" />
|
||||
</map>
|
||||
</property>
|
||||
</bean>
|
||||
]]></programlisting>
|
||||
<para>
|
||||
The channel above also delegates to a queue internally, but the channel is bound
|
||||
to the current thread, so the contents of the queue are as well. That way the thread that
|
||||
sends to the channel will later be able to receive those same Messages, but no other thread
|
||||
would be able to access them. While thread-scoped channels are rarely needed, they can be
|
||||
useful in situations where <classname>DirectChannels</classname> are being used to enforce a
|
||||
single thread of operation but any reply Messages should be sent to a "terminal" channel.
|
||||
If that terminal channel is thread-scoped, the original sending thread can collect its replies from it.
|
||||
</para>
|
||||
<para>
|
||||
Now, since any channel can be scoped, you can define your own scopes in addition to Thread Local.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="channel-interceptors">
|
||||
<title>Channel Interceptors</title>
|
||||
<para>
|
||||
One of the advantages of a messaging architecture is the ability to provide common behavior and capture
|
||||
meaningful information about the messages passing through the system in a non-invasive way. Since the
|
||||
<interfacename>Messages</interfacename> are being sent to and received from
|
||||
<interfacename>MessageChannels</interfacename>, those channels provide an opportunity for intercepting
|
||||
the send and receive operations. The <interfacename>ChannelInterceptor</interfacename> strategy interface
|
||||
provides methods for each of those operations:
|
||||
<programlisting language="java"><![CDATA[public interface ChannelInterceptor {
|
||||
|
||||
Message<?> preSend(Message<?> message, MessageChannel channel);
|
||||
|
||||
void postSend(Message<?> message, MessageChannel channel, boolean sent);
|
||||
|
||||
boolean preReceive(MessageChannel channel);
|
||||
|
||||
Message<?> postReceive(Message<?> message, MessageChannel channel);
|
||||
}]]></programlisting>
|
||||
After implementing the interface, registering the interceptor with a channel is just a matter of calling:
|
||||
<programlisting language="java">channel.addInterceptor(someChannelInterceptor);</programlisting>
|
||||
The methods that return a Message instance can be used for transforming the Message or can return 'null'
|
||||
to prevent further processing (of course, any of the methods can throw a RuntimeException). Also, the
|
||||
<methodname>preReceive</methodname> method can return '<literal>false</literal>' to prevent the receive
|
||||
operation from proceeding.
|
||||
<note>
|
||||
Keep in mind that <methodname>receive()</methodname> calls are only relevant for
|
||||
<interfacename>PollableChannels</interfacename>. In fact the
|
||||
<interfacename>SubscribableChannel</interfacename> interface does not even define a
|
||||
<methodname>receive()</methodname> method. The reason for this is that when a Message is sent to a
|
||||
<interfacename>SubscribableChannel</interfacename> it will be sent directly to one or more subscribers
|
||||
depending on the type of channel (e.g. a PublishSubscribeChannel sends to all of its subscribers). Therefore,
|
||||
the <methodname>preReceive(..)</methodname> and <methodname>postReceive(..)</methodname> interceptor methods
|
||||
are only invoked when the interceptor is applied to a <interfacename>PollableChannel</interfacename>.
|
||||
</note>
|
||||
Spring Integration also provides an implementation of the
|
||||
<ulink url="http://eaipatterns.com/WireTap.html">Wire Tap</ulink> pattern.
|
||||
It is a simple interceptor that sends the Message to another channel without otherwise altering the
|
||||
existing flow. It can be very useful for debugging and monitoring. An example is shown in
|
||||
<xref linkend="channel-wiretap"/>.
|
||||
</para>
|
||||
<para>
|
||||
Because it is rarely necessary to implement all of the interceptor methods, a
|
||||
<classname>ChannelInterceptorAdapter</classname> class is also available for sub-classing. It provides no-op
|
||||
methods (the <literal>void</literal> method is empty, the <classname>Message</classname> returning methods
|
||||
return the Message as-is, and the <literal>boolean</literal> method returns <literal>true</literal>).
|
||||
Therefore, it is often easiest to extend that class and just implement the method(s) that you need as in the
|
||||
following example.
|
||||
<programlisting language="java"><![CDATA[public class CountingChannelInterceptor extends ChannelInterceptorAdapter {
|
||||
|
||||
private final AtomicInteger sendCount = new AtomicInteger();
|
||||
|
||||
@Override
|
||||
public Message<?> preSend(Message<?> message, MessageChannel channel) {
|
||||
sendCount.incrementAndGet();
|
||||
return message;
|
||||
}
|
||||
}]]></programlisting>
|
||||
<tip>
|
||||
The order of invocation for the interceptor methods depends on the type of channel. As described above,
|
||||
the queue-based channels are the only ones where the receive method is intercepted in the first place.
|
||||
Additionally, the relationship between send and receive interception depends on the timing of separate
|
||||
sender and receiver threads. For example, if a receiver is already blocked while waiting for a message
|
||||
the order could be: preSend, preReceive, postReceive, postSend. However, if a receiver polls after the
|
||||
sender has placed a message on the channel and already returned, the order would be: preSend, postSend,
|
||||
(some-time-elapses) preReceive, postReceive. The time that elapses in such a case depends on a number
|
||||
of factors and is therefore generally unpredictable (in fact, the receive may never happen!).
|
||||
Obviously, the type of queue also plays a role (e.g. rendezvous vs. priority). The bottom line is that
|
||||
you cannot rely on the order beyond the fact that preSend will precede postSend and preReceive will
|
||||
precede postReceive.
|
||||
</tip>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="channel-template">
|
||||
<title>MessagingTemplate</title>
|
||||
<para>
|
||||
As you will see when the endpoints and their various configuration options are introduced, Spring Integration
|
||||
provides a foundation for messaging components that enables non-invasive invocation of your application code
|
||||
<emphasis>from the messaging system</emphasis>. However, sometimes it is necessary to invoke the messaging system
|
||||
<emphasis>from your application code</emphasis>. For convenience when implementing such use-cases, Spring
|
||||
Integration provides a <classname>MessagingTemplate</classname> that supports a variety of operations across
|
||||
the Message Channels, including request/reply scenarios. For example, it is possible to send a request
|
||||
and wait for a reply.
|
||||
<programlisting language="java">MessagingTemplate template = new MessagingTemplate();
|
||||
|
||||
Message reply = template.sendAndReceive(someChannel, new GenericMessage("test"));</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
In that example, a temporary anonymous channel would be created internally by the template. The
|
||||
'sendTimeout' and 'receiveTimeout' properties may also be set on the template, and other exchange
|
||||
types are also supported.
|
||||
<programlisting language="java"><![CDATA[public boolean send(final MessageChannel channel, final Message<?> message) { ... }
|
||||
|
||||
public Message<?> sendAndReceive(final MessageChannel channel, final Message<?> request) { .. }
|
||||
|
||||
public Message<?> receive(final PollableChannel<?> channel) { ... }]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
A less invasive approach that allows you to invoke simple interfaces with payload and/or header
|
||||
values instead of Message instances is described in <xref linkend="gateway-proxy"/>.
|
||||
</para>
|
||||
</note>
|
||||
</section>
|
||||
|
||||
<section id="channel-configuration">
|
||||
<title>Configuring Message Channels</title>
|
||||
<para>
|
||||
To create a Message Channel instance, you can use the <channel/> element:
|
||||
<programlisting language="xml"><int:channel id="exampleChannel"/></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The default channel type is <emphasis>Point to Point</emphasis>. To create a
|
||||
<emphasis>Publish Subscribe</emphasis> channel, use the <publish-subscribe-channel/> element:
|
||||
<programlisting language="xml"><int:publish-subscribe-channel id="exampleChannel"/></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
When using the <channel/> element without any sub-elements, it will create a <classname>DirectChannel</classname>
|
||||
instance (a <interfacename>SubscribableChannel</interfacename>).
|
||||
</para>
|
||||
<para>
|
||||
However, you can alternatively provide a variety of <queue/> sub-elements to create any of
|
||||
the pollable channel types (as described in
|
||||
<xref linkend="channel-implementations"/>). Examples of each are shown below.
|
||||
</para>
|
||||
<section id="channel-configuration-directchannel">
|
||||
<title>DirectChannel Configuration</title>
|
||||
<para>
|
||||
As mentioned above, <classname>DirectChannel</classname> is the default type.
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="directChannel"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
A default channel will have a <emphasis>round-robin</emphasis> load-balancer and will also have
|
||||
failover enabled (See the discussion in <xref linkend="channel-implementations-directchannel"/>
|
||||
for more detail). To disable one or both of these, add a <dispatcher/> sub-element and
|
||||
configure the attributes:
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="failFastChannel">
|
||||
<int:dispatcher failover="false"/>
|
||||
</channel>
|
||||
|
||||
<int:channel id="channelWithFixedOrderSequenceFailover">
|
||||
<int:dispatcher load-balancer="none"/>
|
||||
</int:channel>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="channel-datatype-channel">
|
||||
<title>Datatype Channel Configuration</title>
|
||||
<para>
|
||||
There are times when a consumer can only process a particular type of payload and you need to therefore ensure the payload type of input Messages.
|
||||
Of course the first thing that comes to mind is Message Filter. However all that Message Filter will do is filter out Messages that are not compliant with
|
||||
the requirements of the consumer. Another way would be to use a Content Based Router and route Messages with non-compliant data-types to specific
|
||||
Transformers to enforce transformation/conversion to the required data-type. This of course would work, but a simpler way of accomplishing the
|
||||
same thing is to apply the <ulink url="http://www.eaipatterns.com/DatatypeChannel.html">Datatype Channel</ulink> pattern.
|
||||
You can use separate Datatype Channels for each specific payload data-type.
|
||||
</para>
|
||||
<para>
|
||||
To create a Datatype Channel that only
|
||||
accepts messages containing a certain payload type, provide the fully-qualified class name in the
|
||||
channel element's <literal>datatype</literal> attribute:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="numberChannel" datatype="java.lang.Number"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Note that the type check passes for any type that is <emphasis>assignable</emphasis> to the channel's
|
||||
datatype. In other words, the "numberChannel" above would accept messages whose payload is
|
||||
<classname>java.lang.Integer</classname> or <classname>java.lang.Double</classname>. Multiple types can be
|
||||
provided as a comma-delimited list:
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="stringOrNumberChannel" datatype="java.lang.String,java.lang.Number"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
So the 'numberChannel' above will only accept Messages with a data-type of <classname>java.lang.Number</classname>. But what happens
|
||||
if the payload of the Message is not of the required type? It depends on whether you have defined a bean named "integrationConversionService"
|
||||
that is an instance of Spring's <ulink url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html#core-convert-ConversionService-API">Conversion Service</ulink>.
|
||||
If not, then an Exception would be thrown immediately, but if you do have an "integrationConversionService" bean defined, it will be used
|
||||
in an attempt to convert the Message's payload to the acceptable type.
|
||||
</para>
|
||||
<para>
|
||||
You can even register custom converters. For example, let's say you are sending a Message with a String payload to the 'numberChannel' we configured above.
|
||||
<programlisting language="java"><![CDATA[MessageChannel inChannel = context.getBean("numberChannel", MessageChannel.class);
|
||||
inChannel.send(new GenericMessage<String>("5"));]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Typically this would be a perfectly legal operation, however since we are using Datatype Channel the result of such operation would generate an exception:
|
||||
|
||||
<programlisting language="java"><![CDATA[Exception in thread "main" org.springframework.integration.MessageDeliveryException:
|
||||
Channel 'numberChannel'
|
||||
expected one of the following datataypes [class java.lang.Number],
|
||||
but received [class java.lang.String]
|
||||
…]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
And rightfully so since we are requiring the payload type to be a Number while sending a String. So we need something to convert String to a Number.
|
||||
All we need to do is implement a Converter.
|
||||
<programlisting language="java"><![CDATA[public static class StringToIntegerConverter implements Converter<String, Integer> {
|
||||
public Integer convert(String source) {
|
||||
return Integer.parseInt(source);
|
||||
}
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Then, register it as a Converter with the Integration Conversion Service:
|
||||
<programlisting language="java"><![CDATA[<int:converter ref="strToInt"/>
|
||||
|
||||
<bean id="strToInt" class="org.springframework.integration.util.Demo.StringToIntegerConverter"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
When the 'converter' element is parsed, it will create the "integrationConversionService" bean on-demand if one is not already defined.
|
||||
With that Converter in place, the send operation would now be successful since the Datatype Channel will use that Converter to convert the String
|
||||
payload to an Integer.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="channel-configuration-queuechannel">
|
||||
<title>QueueChannel Configuration</title>
|
||||
<para>
|
||||
To create a <classname>QueueChannel</classname>, use the <queue/> sub-element.
|
||||
You may specify the channel's capacity:
|
||||
<programlisting language="xml"><int:channel id="queueChannel">
|
||||
<queue capacity="25"/>
|
||||
</int:channel></programlisting>
|
||||
<note>
|
||||
If you do not provide a value for the 'capacity' attribute on this <queue/> sub-element,
|
||||
the resulting queue will be unbounded. To avoid issues such as OutOfMemoryErrors, it is highly
|
||||
recommended to set an explicit value for a bounded queue.
|
||||
</note>
|
||||
</para>
|
||||
|
||||
<para><emphasis>Persistent QueueChannel Configuration</emphasis></para>
|
||||
|
||||
<para>
|
||||
Since a <classname>QueueChannel</classname> provides the capability to buffer Messages, but does so in-memory only
|
||||
by default, it also introduces a possibility that Messages could be lost in the event of a system failure. To
|
||||
mitigate this risk, a <classname>QueueChannel</classname> may be backed by a persistent implementation of the
|
||||
<classname>MessageGroupStore</classname> strategy interface. For more details on <classname>MessageGroupStore</classname>
|
||||
and <classname>MessageStore</classname> see <xref linkend="message-store" />.
|
||||
</para>
|
||||
<para>
|
||||
When a <classname>QueueChannel</classname> receives a Message, it will add it to the Message Store, and when a Message
|
||||
is polled from a <classname>QueueChannel</classname>, it is removed from the Message Store.
|
||||
</para>
|
||||
<para>
|
||||
By default any <classname>QueueChannel</classname> only stores its Messages in an in-memory Queue
|
||||
and can therefore lead to the lost message scenario mentioned above. However Spring Integration
|
||||
provides a <classname>JdbcMessageStore</classname> to allow a <classname>QueueChannel</classname> to be backed by an RDBMS.
|
||||
</para>
|
||||
<para>
|
||||
You can configure a Message Store for any <classname>QueueChannel</classname> by adding the
|
||||
<code>message-store</code> attribute as shown in the next example.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="dbBackedChannel">
|
||||
<int:queue message-store="messageStore">
|
||||
<int:channel id="myChannel">
|
||||
|
||||
<int-jdbc:message-store id="messageStore" data-source="someDataSource"/>]]></programlisting>
|
||||
|
||||
The above example also shows that <classname>JdbcMessageStore</classname> can be configured with the namespace support
|
||||
provided by the Spring Integration JDBC module. All you need to do is inject any <classname>javax.sql.DataSource</classname>
|
||||
instance. The Spring Integration JDBC module also provides schema DDL for most popular databases. These schemas are located in
|
||||
the <emphasis>org.springframework.integration.jdbc</emphasis> package of that module (spring-integration-jdbc).
|
||||
|
||||
<important>
|
||||
One important feature is that with any transactional persistent store (e.g., JdbcMessageStore), as long as the poller has a transaction configured,
|
||||
a Message removed from the store will only be permanently removed if the transaction completes
|
||||
successfully, otherwise the transaction will roll back and the Message will not be lost.
|
||||
</important>
|
||||
Many other implementations of the Message Store will be available as the growing number of Spring projects
|
||||
related to "NoSQL" data stores provide the underlying support. Of course, you can always provide your own implementation
|
||||
of the MessageGroupStore interface if you cannot find one that meets your particular needs.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="channel-configuration-pubsubchannel">
|
||||
<title>PublishSubscribeChannel Configuration</title>
|
||||
<para>
|
||||
To create a <classname>PublishSubscribeChannel</classname>, use the <publish-subscribe-channel/> element.
|
||||
When using this element, you can also specify the <code>task-executor</code> used for publishing
|
||||
Messages (if none is specified it simply publishes in the sender's thread):
|
||||
<programlisting language="xml"><int:publish-subscribe-channel id="pubsubChannel" task-executor="someExecutor"/></programlisting>
|
||||
If you are providing a <emphasis>Resequencer</emphasis> or <emphasis>Aggregator</emphasis> downstream
|
||||
from a <classname>PublishSubscribeChannel</classname>, then you can set the 'apply-sequence' property
|
||||
on the channel to <code>true</code>. That will indicate that the channel should set the sequence-size
|
||||
and sequence-number Message headers as well as the correlation id prior to passing the Messages along.
|
||||
For example, if there are 5 subscribers, the sequence-size would be set to 5, and the Messages would
|
||||
have sequence-number header values ranging from 1 to 5.
|
||||
<programlisting language="xml"><int:publish-subscribe-channel id="pubsubChannel" apply-sequence="true"/></programlisting>
|
||||
<note>
|
||||
The <code>apply-sequence</code> value is <code>false</code> by default so that a Publish Subscribe Channel
|
||||
can send the exact same Message instances to multiple outbound channels. Since Spring Integration
|
||||
enforces immutability of the payload and header references, the channel creates new Message
|
||||
instances with the same payload reference but different header values when the flag is set to
|
||||
<code>true</code>.
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-configuration-executorchannel">
|
||||
<title>ExecutorChannel</title>
|
||||
<para>
|
||||
To create an <classname>ExecutorChannel</classname>, add the <dispatcher> sub-element along
|
||||
with a <code>task-executor</code> attribute. Its value can reference any <interfacename>TaskExecutor</interfacename>
|
||||
within the context. For example, this enables configuration of a thread-pool for dispatching messages
|
||||
to subscribed handlers. As mentioned above, this does break the "single-threaded" execution context
|
||||
between sender and receiver so that any active transaction context will not be shared by the invocation
|
||||
of the handler (i.e. the handler may throw an Exception, but the send invocation has already returned
|
||||
successfully).
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="executorChannel">
|
||||
<int:dispatcher task-executor="someExecutor"/>
|
||||
</int:channel>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
The <code>load-balancer</code> and <code>failover</code> options are also both available on the <dispatcher/> sub-element
|
||||
as described above in <xref linkend="channel-configuration-directchannel"/>. The same defaults
|
||||
apply as well. So, the channel will have a round-robin load-balancing strategy with failover
|
||||
enabled unless explicit configuration is provided for one or both of those attributes.
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="executorChannelWithoutFailover">
|
||||
<int:dispatcher task-executor="someExecutor" failover="false"/>
|
||||
</int:channel>]]></programlisting>
|
||||
</note>
|
||||
</section>
|
||||
<section id="channel-configuration-prioritychannel">
|
||||
<title>PriorityChannel Configuration</title>
|
||||
<para>
|
||||
To create a <classname>PriorityChannel</classname>, use the <priority-queue/> sub-element:
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="priorityChannel">
|
||||
<int:priority-queue capacity="20"/>
|
||||
</int:channel>]]></programlisting>
|
||||
By default, the channel will consult the <classname>MessagePriority</classname> header of the
|
||||
message. However, a custom <interfacename>Comparator</interfacename> reference may be
|
||||
provided instead. Also, note that the <classname>PriorityChannel</classname> (like the other types)
|
||||
does support the <code>datatype</code> attribute. As with the QueueChannel, it also supports a <code>capacity</code> attribute.
|
||||
The following example demonstrates all of these:
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="priorityChannel" datatype="example.Widget">
|
||||
<int:priority-queue comparator="widgetComparator"
|
||||
capacity="10"/>
|
||||
</int:channel>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-configuration-rendezvouschannel">
|
||||
<title>RendezvousChannel Configuration</title>
|
||||
<para>
|
||||
A <classname>RendezvousChannel</classname> is created when the queue sub-element is
|
||||
a <rendezvous-queue>. It does not provide any additional configuration options to
|
||||
those described above, and its queue does not accept any capacity value since it is a
|
||||
0-capacity direct handoff queue.
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="rendezvousChannel"/>
|
||||
<int:rendezvous-queue/>
|
||||
</int:channel>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-configuration-threadlocalchannel">
|
||||
<title>Scoped Channel Configuration</title>
|
||||
<para>
|
||||
Any channel can be configured with a "scope" attribute.
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="threadLocalChannel" scope="thread"/>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="channel-configuration-interceptors">
|
||||
<title>Channel Interceptor Configuration</title>
|
||||
<para>
|
||||
Message channels may also have interceptors as described in <xref linkend="channel-interceptors"/>. The
|
||||
<interceptors/> sub-element can be added within <channel/> (or the more specific element
|
||||
types). Provide the <code>ref</code> attribute to reference any Spring-managed object that implements the
|
||||
<interfacename>ChannelInterceptor</interfacename> interface:
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="exampleChannel">
|
||||
]]><emphasis><![CDATA[<int:interceptors>
|
||||
<ref bean="trafficMonitoringInterceptor"/>
|
||||
</int:interceptors>]]></emphasis><![CDATA[
|
||||
</int:channel>]]></programlisting>
|
||||
In general, it is a good idea to define the interceptor implementations in a separate location since they
|
||||
usually provide common behavior that can be reused across multiple channels.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="global-channel-configuration-interceptors">
|
||||
<title>Global Channel Interceptor Configuration</title>
|
||||
|
||||
<titleabbrev id="global-channel-interceptor">Global Channel Interceptor</titleabbrev>
|
||||
|
||||
<para>
|
||||
Channel Interceptors provide a clean and concise way of applying cross-cutting behavior per individual channel.
|
||||
If the same behavior should be applied on multiple channels, configuring the same set of interceptors for
|
||||
each channel <emphasis>would not be</emphasis> the most efficient way. To avoid repeated configuration while
|
||||
also enabling interceptors to apply to multiple channels, Spring Integration provides
|
||||
<emphasis>Global Interceptors</emphasis>.
|
||||
|
||||
Look at the example below:
|
||||
<programlisting language="xml"><![CDATA[<int:channel-interceptor pattern="input*, bar*, foo" order="3">
|
||||
<bean class="foo.barSampleInterceptor"/>
|
||||
</int:channel-interceptor>]]></programlisting>
|
||||
or
|
||||
<programlisting language="xml"><![CDATA[<int:channel-interceptor ref="myInterceptor" pattern="input*, bar*, foo" order="3"/>
|
||||
|
||||
<bean id="myInterceptor" class="foo.barSampleInterceptor"/>]]></programlisting>
|
||||
Each <channel-interceptor/> element allows you to define a global interceptor which will be applied on all
|
||||
channels that match any patterns defined via the <code>pattern</code> attribute. In the above case the
|
||||
global interceptor will be applied on the
|
||||
'foo' channel and all other channels that begin with 'bar' or 'input'.
|
||||
The <emphasis>order</emphasis> attribute allows you to manage where this interceptor will be injected if there
|
||||
are multiple interceptors on a given channel.
|
||||
For example, channel 'inputChannel' could have individual interceptors configured locally (see below):
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="inputChannel">
|
||||
<int:interceptors>
|
||||
<int:wire-tap channel="logger"/>
|
||||
</int:interceptors>
|
||||
</int:channel>]]></programlisting>
|
||||
A reasonable question is how will a global interceptor be injected in relation to other interceptors
|
||||
configured locally or through other global interceptor definitions? The current implementation provides
|
||||
a very simple mechanism for defining the order of interceptor execution.
|
||||
A positive number in the <code>order</code> attribute will ensure interceptor injection
|
||||
after any existing interceptors and a negative number will ensure that the interceptor is injected before
|
||||
existing interceptors.
|
||||
This means that in the above example, the global interceptor will be injected <emphasis>AFTER</emphasis>
|
||||
(since its order is greater than 0)
|
||||
the 'wire-tap' interceptor configured locally. If there were another global interceptor with a matching
|
||||
<code>pattern</code>, its order would be determined by comparing the values of the <code>order</code> attribute.
|
||||
To inject a global interceptor <emphasis>BEFORE</emphasis> the existing interceptors, use a negative value for the <code>order</code> attribute.
|
||||
</para>
|
||||
<note>
|
||||
Note that both the <code>order</code> and <code>pattern</code> attributes are optional. The default value
|
||||
for <code>order</code> will be 0 and for <code>pattern</code>, the default is '*' (to match all channels).
|
||||
</note>
|
||||
</section>
|
||||
|
||||
<section id="channel-wiretap">
|
||||
<title>Wire Tap</title>
|
||||
<para>
|
||||
As mentioned above, Spring Integration provides a simple <emphasis>Wire Tap</emphasis> interceptor out of
|
||||
the box. You can configure a <emphasis>Wire Tap</emphasis> on any channel within an <interceptors/> element.
|
||||
This is especially useful for debugging, and can be used in conjunction with Spring Integration's logging
|
||||
Channel Adapter as follows: <programlisting language="xml"><![CDATA[ <int:channel id="in">
|
||||
<int:interceptors>
|
||||
<int:wire-tap channel="logger"/>
|
||||
</int:interceptors>
|
||||
</int:channel>
|
||||
|
||||
<int:logging-channel-adapter id="logger" level="DEBUG"/>]]></programlisting>
|
||||
<tip>
|
||||
The 'logging-channel-adapter' also accepts an 'expression' attribute so that you can evaluate
|
||||
a SpEL expression against 'payload' and/or 'headers' variables. Alternatively, to simply log
|
||||
the full Message toString() result, provide a value of "true" for the 'log-full-message' attribute.
|
||||
That is <code>false</code> by default so that only the payload is logged. Setting that to
|
||||
<code>true</code> enables logging of all headers in addition to the payload. The 'expression'
|
||||
option does provide the most flexibility, however (e.g. expression="payload.user.name").
|
||||
</tip>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>A little more on Wire Tap</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
One of the common misconceptions about the wire tap and other similar components (<xref linkend="message-publishing-config"/>)
|
||||
is that they are automatically asynchronous in nature. Wire-tap as a component is not
|
||||
invoked asynchronously be default. Instead, Spring Integration focuses on a single unified
|
||||
approach to configuring asynchronous behavior: the Message Channel.
|
||||
|
||||
What makes certain parts of the message flow <emphasis>sync</emphasis> or <emphasis>async</emphasis>
|
||||
is the type of <emphasis>Message Channel</emphasis> that has been configured within that flow. That
|
||||
is one of the primary benefits of the Message Channel abstraction.
|
||||
From the inception of the framework, we have always emphasized the need and the value of the
|
||||
<emphasis>Message Channel</emphasis> as a first-class citizen of the framework. It is not
|
||||
just an internal, implicit realization of the EIP pattern, it is fully exposed as a configurable
|
||||
component to the end user.
|
||||
|
||||
So, the Wire-tap component is ONLY responsible for performing the following 3 tasks:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>intercept a message flow by tapping into a channel (e.g., channelA)</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>grab each message</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>send the message to another channel (e.g., channelB)</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
It is essentially a variation of the Bridge, but it is encapsulated within a channel definition
|
||||
(and hence easier to enable and disable without disrupting a flow). Also, unlike the bridge, it
|
||||
basically forks another message flow. Is that flow <emphasis>synchronous</emphasis> or
|
||||
<emphasis>asynchronous</emphasis>? The answer simply depends on the type of <emphasis>Message Channel</emphasis>
|
||||
that 'channelB' is. And, now you know that we have: <emphasis>Direct Channel</emphasis>,
|
||||
<emphasis>Pollable Channel</emphasis>, and <emphasis>Executor Channel</emphasis> as options.
|
||||
The last two do break the thread boundary making communication via such channels
|
||||
<emphasis>asynchronous</emphasis> simply because the dispatching of the message from that channel
|
||||
to its subscribed handlers happens on a different thread than the one used to send the message to that
|
||||
channel. That is what is going to make your wire-tap flow <emphasis>sync</emphasis> or <emphasis>async</emphasis>.
|
||||
It is consistent with other components within the framework (e.g., Message Publisher) and actually
|
||||
brings a level of consistency and simplicity by sparing you from worrying in advance (other than writing
|
||||
thread safe code) whether a particular piece of code should be implemented as <emphasis>sync</emphasis> or
|
||||
<emphasis>async</emphasis>. The actual wiring of two pieces of code (component A and component B) via
|
||||
<emphasis>Message Channel</emphasis> is what makes their collaboration <emphasis>sync</emphasis> or
|
||||
<emphasis>async</emphasis>. You may even want to change from <emphasis>sync</emphasis> to
|
||||
<emphasis>async</emphasis> in the future and <emphasis>Message Channel</emphasis> is what's going
|
||||
to allow you to do it swiftly without ever touching the code.</para>
|
||||
|
||||
<para>One final point regarding the Wire Tap is that, despite the rationale provided above for not
|
||||
being async be default, one should keep in mind it is usually desirable to hand off the Message as
|
||||
soon as possible. Therefore, it would be quite common to use an asynchronous channel option as the
|
||||
wire-tap's outbound channel. Nonetheless, another reason that we do not enforce asynchronous behavior
|
||||
by default is that you might not want to break a transactional boundary. Perhaps you are using the Wire Tap
|
||||
for auditing purposes, and you DO want the audit Messages to be sent within the original transaction.
|
||||
As an example, you might connect the wire-tap to a JMS outbound-channel-adapter. That way, you get the
|
||||
best of both worlds: 1) the sending of a JMS Message can occur within the transaction while
|
||||
2) it is still a "fire-and-forget" action thereby preventing any noticeable delay in the main message flow.
|
||||
</para>
|
||||
</section>
|
||||
<section id="channel-global-wiretap">
|
||||
<title>Global Wire Tap Configuration</title>
|
||||
<para>It is possible to configure a global wire tap as a special case of the <xref linkend="global-channel-configuration-interceptors" endterm="global-channel-interceptor"/>. Simply configure a top level <code>wire-tap</code> element. Now, in addition to the normal <code>wire-tap</code> namespace support, the <code>pattern</code> and <code>order</code> attributes are supported and work in exactly the same way as with the <code>channel-interceptor</code>
|
||||
<programlisting language="xml"><![CDATA[<int:wire-tap pattern="input*, bar*, foo" order="3" channel="wiretapChannel"/>]]></programlisting>
|
||||
</para>
|
||||
<tip>A global wire tap provides a convenient way to configure a single channel wire tap externally without modifying the existing channel configuration. Simply set the <code>pattern</code> attribute to the target channel name. For example, This technique may be used to configure a test case to verify messages on a channel.
|
||||
</tip>
|
||||
</section>
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
|
||||
<section id="channel-special-channels">
|
||||
<title>Special Channels</title>
|
||||
<para>
|
||||
If namespace support is enabled, there are two special channels defined within the application context by default:
|
||||
<code>errorChannel</code> and <code>nullChannel</code>. The 'nullChannel' acts like <code>/dev/null</code>,
|
||||
simply logging any Message sent to it at DEBUG level and returning immediately. Any time you face channel
|
||||
resolution errors for a reply that you don't care about, you can set the affected component's <code>output-channel</code> attribute
|
||||
to 'nullChannel' (the name 'nullChannel' is reserved within the application context). The 'errorChannel' is
|
||||
used internally for sending error messages and may be overridden with a custom configuration. This is
|
||||
discussed in greater detail in <xref linkend="namespace-errorhandler"/>.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
265
src/reference/docbook/claim-check.xml
Normal file
@@ -0,0 +1,265 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="claim-check"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Claim Check</title>
|
||||
|
||||
<section id="claim-check-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
In the earlier sections we've covered several Content Enricher type components that help you deal with situations where a
|
||||
message is missing a piece of data. We also discussed Content Filtering which lets you remove data items from a message.
|
||||
However there are times when we want to hide data temporarily. For example, in a distributed system we may receive a
|
||||
Message with a very large payload. Some intermittent message processing steps may not need access to this payload and some may only
|
||||
need to access certain headers, so carrying the large Message payload through each processing step may cause performance degradation,
|
||||
may produce a security risk, and may make debugging more difficult.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The <link href="http://www.eaipatterns.com/StoreInLibrary.html">Claim Check</link> pattern describes a mechanism that allows you
|
||||
to store data in a well known place while only maintaining a pointer (Claim Check) to where that data is located. You can pass that
|
||||
pointer around as a payload of a new Message thereby allowing any component within the message flow to get the actual data as soon as
|
||||
it needs it. This approach is very similar to the Certified Mail process where you'll get a Claim Check in your mailbox and
|
||||
would have to go to the Post Office to claim your actual package. Of course it's also the same idea as baggage-claim on a flight
|
||||
or in a hotel.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration provides two types of Claim Check transformers:
|
||||
</para>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem><emphasis>Incoming Claim Check Transformer</emphasis></listitem>
|
||||
<listitem><emphasis>Outgoing Claim Check Transformer</emphasis></listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<para>
|
||||
Convenient namespace-based mechanisms are available to configure them.
|
||||
</para>
|
||||
|
||||
</section>
|
||||
<section id="claim-check-in">
|
||||
<title>Incoming Claim Check Transformer</title>
|
||||
|
||||
<para>
|
||||
An <emphasis>Incoming Claim Check Transformer</emphasis> will transform an incoming Message by storing it in the Message Store
|
||||
identified by its <code>message-store</code> attribute.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:claim-check-in id="checkin"
|
||||
input-channel="checkinChannel"
|
||||
message-store="testMessageStore"
|
||||
output-channel="output"/>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the above configuration the Message that is received on the <code>input-channel</code> will be persisted to the
|
||||
Message Store identified with the <code>message-store</code> attribute and indexed with generated ID. That ID is the
|
||||
Claim Check for that Message.
|
||||
The Claim Check will also become the payload of the new (transformed) Message that will be sent to the <code>output-channel</code>.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Now, lets assume that at some point you do need access to the actual Message. You can of course access the Message Store
|
||||
manually and get the contents of the Message, or you can use the same approach as before except now you will be transforming
|
||||
the Claim Check to the actual Message by using an <emphasis>Outgoing Claim Check Transformer</emphasis>.
|
||||
</para>
|
||||
<para>
|
||||
Here is an overview of all available parameters of an Incoming Claim
|
||||
Check Transformer:
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:claim-check-in auto-startup="true" ]]><co id="claimcheck-in-xml01-co" linkends="claimcheck-in-xml01" /><![CDATA[
|
||||
id="" ]]><co id="claimcheck-in-xml02-co" linkends="claimcheck-in-xml02" /><![CDATA[
|
||||
input-channel="" ]]><co id="claimcheck-in-xml03-co" linkends="claimcheck-in-xml03" /><![CDATA[
|
||||
message-store="messageStore" ]]><co id="claimcheck-in-xml04-co" linkends="claimcheck-in-xml04" /><![CDATA[
|
||||
order="" ]]><co id="claimcheck-in-xml05-co" linkends="claimcheck-in-xml05" /><![CDATA[
|
||||
output-channel="" ]]><co id="claimcheck-in-xml06-co" linkends="claimcheck-in-xml06" /><![CDATA[
|
||||
send-timeout=""> ]]><co id="claimcheck-in-xml07-co" linkends="claimcheck-in-xml07" /><![CDATA[
|
||||
<int:poller></int:poller> ]]><co id="claimcheck-in-xml08-co" linkends="claimcheck-in-xml08" /><![CDATA[
|
||||
</int:claim-check-in>]]></programlisting>
|
||||
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="claimcheck-in-xml01-co" id="claimcheck-in-xml01">
|
||||
<para>Lifecycle attribute signaling if this component should
|
||||
be started during Application Context startup. Defaults
|
||||
to true. Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-in-xml02-co" id="claimcheck-in-xml02">
|
||||
<para>Id identifying the underlying bean definition (<classname>MessageTransformingHandler</classname>).
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-in-xml03-co" id="claimcheck-in-xml03">
|
||||
<para>The receiving Message channel of this endpoint.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-in-xml04-co" id="claimcheck-in-xml04">
|
||||
<para>Reference to the MessageStore to be used by this Claim
|
||||
Check transformer. If not specified, the default reference
|
||||
will be to a bean named <emphasis>messageStore</emphasis>.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-in-xml05-co" id="claimcheck-in-xml05">
|
||||
<para>Specifies the order for invocation when this endpoint is
|
||||
connected as a subscriber to a channel. This is particularly
|
||||
relevant when that channel is using a <emphasis>failover</emphasis>
|
||||
dispatching strategy. It has no effect when this endpoint
|
||||
itself is a Polling Consumer for a channel with a queue.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-in-xml06-co" id="claimcheck-in-xml06">
|
||||
<para>Identifies the Message channel where Message will be sent
|
||||
after its being processed by this endpoint.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-in-xml07-co" id="claimcheck-in-xml07">
|
||||
<para>Specify the maximum amount of time in milliseconds to wait
|
||||
when sending a reply Message to the output channel. By default
|
||||
the send will block for one second.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-in-xml08-co" id="claimcheck-in-xml08">
|
||||
<para>Defines a poller. Element is not available inside
|
||||
a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="claim-check-out">
|
||||
<title>Outgoing Claim Check Transformer</title>
|
||||
|
||||
<para>
|
||||
An <emphasis>Outgoing Claim Check Transformer</emphasis> allows you to transform a Message with a Claim Check payload
|
||||
into a Message with the original content as its payload.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:claim-check-out id="checkout"
|
||||
input-channel="checkoutChannel"
|
||||
message-store="testMessageStore"
|
||||
output-channel="output"/>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the above configuration, the Message that is received on the <code>input-channel</code> should have a Claim Check as its payload
|
||||
and the <emphasis>Outgoing Claim Check Transformer</emphasis> will transform it into a Message with the original payload by simply
|
||||
querying the Message store for a Message identified by the provided Claim Check. It then sends the newly checked-out Message to the
|
||||
<code>output-channel</code>.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Here is an overview of all available parameters of an Outgoing Claim
|
||||
Check Transformer:
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:claim-check-out auto-startup="true" ]]><co id="claimcheck-out-xml01-co" linkends="claimcheck-out-xml01" /><![CDATA[
|
||||
id="" ]]><co id="claimcheck-out-xml02-co" linkends="claimcheck-out-xml02" /><![CDATA[
|
||||
input-channel="" ]]><co id="claimcheck-out-xml03-co" linkends="claimcheck-out-xml03" /><![CDATA[
|
||||
message-store="messageStore" ]]><co id="claimcheck-out-xml04-co" linkends="claimcheck-out-xml04" /><![CDATA[
|
||||
order="" ]]><co id="claimcheck-out-xml05-co" linkends="claimcheck-out-xml05" /><![CDATA[
|
||||
output-channel="" ]]><co id="claimcheck-out-xml06-co" linkends="claimcheck-out-xml06" /><![CDATA[
|
||||
remove-message="false" ]]><co id="claimcheck-out-xml07-co" linkends="claimcheck-out-xml07" /><![CDATA[
|
||||
send-timeout=""> ]]><co id="claimcheck-out-xml08-co" linkends="claimcheck-out-xml08" /><![CDATA[
|
||||
<int:poller></int:poller> ]]><co id="claimcheck-out-xml09-co" linkends="claimcheck-out-xml09" /><![CDATA[
|
||||
</int:claim-check-out>]]></programlisting>
|
||||
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="claimcheck-out-xml01-co" id="claimcheck-out-xml01">
|
||||
<para>Lifecycle attribute signaling if this component should
|
||||
be started during Application Context startup. Defaults
|
||||
to true. Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml02-co" id="claimcheck-out-xml02">
|
||||
<para>Id identifying the underlying bean definition (<classname>MessageTransformingHandler</classname>).
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml03-co" id="claimcheck-out-xml03">
|
||||
<para>The receiving Message channel of this endpoint.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml04-co" id="claimcheck-out-xml04">
|
||||
<para>Reference to the MessageStore to be used by this Claim
|
||||
Check transformer. If not specified, the default reference
|
||||
will be to a bean named <emphasis>messageStore</emphasis>.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml05-co" id="claimcheck-out-xml05">
|
||||
<para>Specifies the order for invocation when this endpoint is
|
||||
connected as a subscriber to a channel. This is particularly
|
||||
relevant when that channel is using a <emphasis>failover</emphasis>
|
||||
dispatching strategy. It has no effect when this endpoint
|
||||
itself is a Polling Consumer for a channel with a queue.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml06-co" id="claimcheck-out-xml06">
|
||||
<para>Identifies the Message channel where Message will be sent
|
||||
after its being processed by this endpoint.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml07-co" id="claimcheck-out-xml07">
|
||||
<para>If set to <code>true</code> the Message will be removed from the
|
||||
MessageStore by this transformer. Useful when Message can
|
||||
be "claimed" only once. Defaults to <code>false</code>.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml08-co" id="claimcheck-out-xml08">
|
||||
<para>Specify the maximum amount of time in milliseconds to wait
|
||||
when sending a reply Message to the output channel. By default
|
||||
the send will block for one second.
|
||||
Attribute is not available inside a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
<callout arearefs="claimcheck-out-xml09-co" id="claimcheck-out-xml09">
|
||||
<para>Defines a poller. Element is not available inside
|
||||
a <code>Chain</code> element.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
</calloutlist>
|
||||
</para>
|
||||
|
||||
<para><emphasis>Claim Once</emphasis></para>
|
||||
<para>
|
||||
There are scenarios when a particular message must be claimed only once. As an analogy, consider the airplane luggage check-in/out process.
|
||||
Checking-in your luggage on departure and and then claiming it on arrival is a classic example of such a scenario.
|
||||
Once the luggage has been claimed, it can not be claimed again without first checking it back in. To accommodate such cases, we
|
||||
introduced a <code>remove-message</code> boolean attribute on the <code>claim-check-out</code> transformer. This attribute is
|
||||
set to <code>false</code> by default. However, if set to <code>true</code>, the claimed Message will be removed
|
||||
from the MessageStore, so that it can no longer be claimed again.
|
||||
</para>
|
||||
<para>
|
||||
This is also something to consider in terms of storage space, especially
|
||||
in the case of the in-memory Map-based <classname>SimpleMessageStore</classname>, where failing to remove the Messages
|
||||
could ultimately lead to an <classname>OutOfMemoryException</classname>.
|
||||
Therefore, if you don't expect multiple claims to be made, it's recommended
|
||||
that you set the <code>remove-message</code> attribute's value to <code>true</code>.
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:claim-check-out id="checkout"
|
||||
input-channel="checkoutChannel"
|
||||
message-store="testMessageStore"
|
||||
output-channel="output"
|
||||
remove-message="true"/>]]></programlisting>
|
||||
</section>
|
||||
<section>
|
||||
<title>A word on Message Store</title>
|
||||
<para>
|
||||
Although we rarely care about the details of the claim checks as long as they work, it is still worth knowing that
|
||||
the current implementation of the actual Claim Check (the pointer) in Spring Integration is a UUID to ensure uniqueness.
|
||||
</para>
|
||||
<para>
|
||||
<classname>org.springframework.integration.store.MessageStore</classname> is a strategy interface for storing and retrieving messages.
|
||||
Spring Integration provides two convenient implementations of it. <classname>SimpleMessageStore</classname>: an in-memory, Map-based
|
||||
implementation (the default, good for testing) and <classname>JdbcMessageStore</classname>: an implementation that uses a relational
|
||||
database via JDBC.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
488
src/reference/docbook/configuration.xml
Normal file
@@ -0,0 +1,488 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<appendix xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="configuration"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Configuration</title>
|
||||
<section id="configuration-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
Spring Integration offers a number of configuration options. Which option you choose depends upon your particular
|
||||
needs and at what level you prefer to work. As with the Spring framework in general, it is also possible to mix
|
||||
and match the various techniques according to the particular problem at hand. For example, you may choose the
|
||||
XSD-based namespace for the majority of configuration combined with a handful of objects that are configured with
|
||||
annotations. As much as possible, the two provide consistent naming. XML elements defined by the XSD schema will
|
||||
match the names of annotations, and the attributes of those XML elements will match the names of annotation
|
||||
properties. Direct usage of the API is of course always an option, but we expect that most users will choose one
|
||||
of the higher-level options, or a combination of the namespace-based and annotation-driven configuration.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="configuration-namespace">
|
||||
<title>Namespace Support</title>
|
||||
<para>
|
||||
Spring Integration components can be configured with XML elements that map directly to the terminology and
|
||||
concepts of enterprise integration. In many cases, the element names match those of the
|
||||
<ulink url="http://www.eaipatterns.com">Enterprise Integration Patterns</ulink>.
|
||||
</para>
|
||||
<para>
|
||||
To enable Spring Integration's core namespace support within your Spring configuration files, add the following
|
||||
namespace reference and schema mapping in your top-level 'beans' element:
|
||||
<programlisting language="xml"><![CDATA[<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
]]><emphasis>xmlns:int="http://www.springframework.org/schema/integration"</emphasis><![CDATA[
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
]]><emphasis>http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd"</emphasis>></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
You can choose any name after "xmlns:"; <emphasis>int</emphasis> is used here for clarity, but you might
|
||||
prefer a shorter abbreviation. Of course if you are using an XML-editor or IDE support, then the availability of
|
||||
auto-completion may convince you to keep the longer name for clarity. Alternatively, you can create configuration
|
||||
files that use the Spring Integration schema as the primary namespace:
|
||||
<programlisting language="xml"><emphasis><beans:beans xmlns="http://www.springframework.org/schema/integration"</emphasis><![CDATA[
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
]]><emphasis>xmlns:beans="http://www.springframework.org/schema/beans"</emphasis><![CDATA[
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd">]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
When using this alternative, no prefix is necessary for the Spring Integration elements. On the other hand, if
|
||||
you want to define a generic Spring "bean" within the same configuration file, then a prefix would be required
|
||||
for the bean element (<beans:bean ... />). Since it is generally a good idea to modularize the
|
||||
configuration files themselves based on responsibility and/or architectural layer, you may find it appropriate to
|
||||
use the latter approach in the integration-focused configuration files, since generic beans are seldom necessary
|
||||
within those same files. For purposes of this documentation, we will assume the "integration" namespace is
|
||||
primary.
|
||||
</para>
|
||||
<para>
|
||||
Many other namespaces are provided within the Spring Integration distribution. In fact, each adapter type (JMS,
|
||||
File, etc.) that provides namespace support defines its elements within a separate schema. In order to use these
|
||||
elements, simply add the necessary namespaces with an "xmlns" entry and the corresponding "schemaLocation" mapping.
|
||||
For example, the following root element shows several of these namespace declarations:
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:int="http://www.springframework.org/schema/integration"
|
||||
xmlns:int-file="http://www.springframework.org/schema/integration/file"
|
||||
xmlns:int-jms="http://www.springframework.org/schema/integration/jms"
|
||||
xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
|
||||
xmlns:int-rmi="http://www.springframework.org/schema/integration/rmi"
|
||||
xmlns:int-ws="http://www.springframework.org/schema/integration/ws"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd
|
||||
http://www.springframework.org/schema/integration/file
|
||||
http://www.springframework.org/schema/integration/file/spring-integration-file.xsd
|
||||
http://www.springframework.org/schema/integration/jms
|
||||
http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
|
||||
http://www.springframework.org/schema/integration/mail
|
||||
http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
|
||||
http://www.springframework.org/schema/integration/rmi
|
||||
http://www.springframework.org/schema/integration/rmi/spring-integration-rmi.xsd
|
||||
http://www.springframework.org/schema/integration/ws
|
||||
http://www.springframework.org/schema/integration/ws/spring-integration-ws.xsd">
|
||||
...
|
||||
</beans>]]></programlisting>
|
||||
The reference manual provides specific examples of the various elements in their corresponding chapters. Here, the
|
||||
main thing to recognize is the consistency of the naming for each namespace URI and schema location.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="namespace-taskscheduler">
|
||||
<title>Configuring the Task Scheduler</title>
|
||||
<para>
|
||||
|
||||
In Spring Integration, the ApplicationContext plays the central role of a Message Bus, and there are only a
|
||||
couple configuration options to consider. First, you may want to control the central TaskScheduler instance.
|
||||
You can do so by providing a single bean with the name "taskScheduler". This is also defined as a constant:
|
||||
<programlisting><![CDATA[ IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME ]]></programlisting>
|
||||
By default Spring Integration relies on an instance of ThreadPoolTaskScheduler as described in the <ulink url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html">Task Execution and Scheduling</ulink>
|
||||
section of the Spring Framework reference manual. That default TaskScheduler will startup automatically with a
|
||||
pool of 10 threads. If you provide your own TaskScheduler instance instead, you can set the 'autoStartup' property
|
||||
to <emphasis>false</emphasis>, and/or you can provide your own pool size value.
|
||||
</para>
|
||||
<para>
|
||||
When Polling Consumers provide an explicit task-executor reference in their configuration, the invocation of
|
||||
the handler methods will happen within that executor's thread pool and not the main scheduler pool. However,
|
||||
when no task-executor is provided for an endpoint's poller, it will be invoked by one of the main scheduler's
|
||||
threads.
|
||||
<note>
|
||||
An endpoint is a <emphasis>Polling Consumer</emphasis> if its input channel is one of the queue-based
|
||||
(i.e. pollable) channels. On the other hand, <emphasis>Event Driven Consumers</emphasis> are those whose
|
||||
input channels have dispatchers instead of queues (i.e. they are subscribable). Such endpoints have no
|
||||
poller configuration since their handlers will be invoked directly.
|
||||
</note>
|
||||
<para>
|
||||
The next section will describe what happens if Exceptions occur within the asynchronous invocations.
|
||||
</para>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="namespace-errorhandler">
|
||||
<title>Error Handling</title>
|
||||
<para>
|
||||
As described in the overview at the very beginning of this manual, one of the main motivations behind a
|
||||
Message-oriented framework like Spring Integration is to promote loose-coupling between components. The
|
||||
Message Channel plays an important role in that producers and consumers do not have to know about each
|
||||
other. However, the advantages also have some drawbacks. Some things become more complicated in a very
|
||||
loosely coupled environment, and one example is error handling.
|
||||
</para>
|
||||
<para>
|
||||
When sending a Message to a channel, the component that ultimately handles that Message may or may not
|
||||
be operating within the same thread as the sender. If using a simple default DirectChannel (with the
|
||||
<channel> element that has no <queue> sub-element and no 'task-executor' attribute), the
|
||||
Message-handling will occur in the same thread as the Message-sending. In that case, if an Exception
|
||||
is thrown, it can be caught by the sender (or it may propagate past the sender if it is an uncaught
|
||||
RuntimeException). So far, everything is fine. This is the same behavior as an Exception-throwing
|
||||
operation in a normal call stack. However, when adding the asynchronous aspect, things become much
|
||||
more complicated. For instance, if the 'channel' element <emphasis>does</emphasis> provide a 'queue'
|
||||
sub-element, then the component that handles the Message <emphasis>will</emphasis> be operating in a
|
||||
different thread than the sender. The sender may have dropped the Message into the channel and moved
|
||||
on to other things. There is no way for the Exception to be thrown directly back to that sender using
|
||||
standard Exception throwing techniques. Instead, to handle errors for asynchronous processes requires
|
||||
an asynchronous error-handling mechanism as well.
|
||||
</para>
|
||||
<para>
|
||||
Spring Integration supports error handling for its components by publishing errors to a Message Channel.
|
||||
Specifically, the Exception will become the payload of a Spring Integration Message. That Message will
|
||||
then be sent to a Message Channel that is resolved in a way that is similar to the 'replyChannel'
|
||||
resolution. First, if the request Message being handled at the time the Exception occurred contains
|
||||
an 'errorChannel' header (the header name is defined in the constant: MessageHeaders.ERROR_CHANNEL),
|
||||
the ErrorMessage will be sent to that channel. Otherwise, the error handler will send to a "global"
|
||||
channel whose bean name is "errorChannel" (this is also defined as a constant:
|
||||
IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME).
|
||||
</para>
|
||||
<para>
|
||||
Whenever relying on Spring Integration's XML namespace support, a default "errorChannel" bean will be
|
||||
created behind the scenes. However, you can just as easily define your own if you want to control the
|
||||
settings.
|
||||
<programlisting language="xml"><![CDATA[ <int:channel id="errorChannel">
|
||||
<int:queue capacity="500"/>
|
||||
</int:channel>]]></programlisting>
|
||||
<note>
|
||||
The default "errorChannel" is a PublishSubscribeChannel.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
The most important thing to understand here is that the messaging-based error handling will only apply
|
||||
to Exceptions that are thrown by a Spring Integration task that is executing within a TaskExecutor.
|
||||
This does <emphasis>not</emphasis> apply to Exceptions thrown by a handler that is operating within
|
||||
the same thread as the sender (e.g. through a DirectChannel as described above).
|
||||
</para>
|
||||
<note>
|
||||
When Exceptions occur in a scheduled poller task's execution, those exceptions will be wrapped in
|
||||
<classname>ErrorMessages</classname> and sent to the 'errorChannel' as well.
|
||||
</note>
|
||||
<para>
|
||||
To enable global error handling, simply register a handler on that channel. For example, you can configure
|
||||
Spring Integration's <classname>ErrorMessageExceptionTypeRouter</classname> as the handler of an endpoint
|
||||
that is subscribed to the 'errorChannel'. That router can then spread the error messages across multiple
|
||||
channels based on <classname>Exception</classname> type.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="annotations">
|
||||
<title>Annotation Support</title>
|
||||
<para>
|
||||
In addition to the XML namespace support for configuring Message Endpoints,
|
||||
it is also possible to use annotations. First, Spring Integration provides
|
||||
the class-level <interfacename>@MessageEndpoint</interfacename> as a
|
||||
<emphasis>stereotype</emphasis> annotation, meaning that it is itself
|
||||
annotated with Spring's <interfacename>@Component</interfacename> annotation
|
||||
and is therefore recognized automatically as a bean definition when using
|
||||
Spring component-scanning.
|
||||
</para>
|
||||
<para>
|
||||
Even more important are the various method-level annotations that indicate
|
||||
the annotated method is capable of handling a message. The following example
|
||||
demonstrates both:
|
||||
<programlisting language="java">@MessageEndpoint
|
||||
public class FooService {
|
||||
|
||||
@ServiceActivator
|
||||
public void processMessage(Message message) {
|
||||
...
|
||||
}
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Exactly what it means for the method to "handle" the Message depends on the
|
||||
particular annotation. The following annotations are available in Spring Integration:
|
||||
<itemizedlist>
|
||||
<listitem>@Aggregator</listitem>
|
||||
<listitem>@ChannelAdapter</listitem>
|
||||
<listitem>@Filter</listitem>
|
||||
<listitem>@Router</listitem>
|
||||
<listitem>@ServiceActivator</listitem>
|
||||
<listitem>@Splitter</listitem>
|
||||
<listitem>@Transformer</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>The behavior of each is described in its own chapter or section within
|
||||
this reference.</para>
|
||||
<note>
|
||||
If you are using XML configuration in combination with annotations, the
|
||||
<interfacename>@MessageEndpoint</interfacename> annotation is not required.
|
||||
If you want to configure a POJO reference from the "ref" attribute of a
|
||||
<service-activator/> element, it is sufficient to provide the
|
||||
method-level annotations. In that case, the annotation prevents ambiguity
|
||||
even when no "method" attribute exists on the <service-activator/> element.
|
||||
</note>
|
||||
<para>
|
||||
In most cases, the annotated handler method should not require the
|
||||
<classname>Message</classname> type as its parameter. Instead, the method
|
||||
parameter type can match the message's payload type.
|
||||
<programlisting language="java">public class FooService {
|
||||
|
||||
@ServiceActivator
|
||||
public void bar(<emphasis>Foo foo</emphasis>) {
|
||||
...
|
||||
}
|
||||
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
When the method parameter should be mapped from a value in the <classname>MessageHeaders</classname>, another
|
||||
option is to use the parameter-level <interfacename>@Header</interfacename> annotation. In general, methods
|
||||
annotated with the Spring Integration annotations can either accept the <classname>Message</classname> itself, the
|
||||
message payload, or a header value (with @Header) as the parameter. In fact, the method can accept a combination,
|
||||
such as:
|
||||
<programlisting language="java">public class FooService {
|
||||
|
||||
@ServiceActivator
|
||||
public void bar(String payload, @Header("x") int valueX, @Header("y") int valueY) {
|
||||
...
|
||||
}
|
||||
|
||||
}</programlisting>
|
||||
There is also a @Headers annotation that provides all of the Message headers as a Map:
|
||||
<programlisting language="java">public class FooService {
|
||||
|
||||
@ServiceActivator
|
||||
public void bar(String payload, @Headers Map<String, Object> headerMap) {
|
||||
...
|
||||
}
|
||||
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
<note>
|
||||
The value of the annotation can also be a SpEL expression (e.g., 'payload.getCustomerId()') which is quite useful when
|
||||
the name of the header has to be dynamically computed. It also provides an optional 'required' property which
|
||||
specifies whether the attribute value must be available within the header. The default value for 'required' is <code>true</code>.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
For several of these annotations, when a Message-handling method returns a non-null value, the endpoint will
|
||||
attempt to send a reply. This is consistent across both configuration options (namespace and annotations) in
|
||||
that such an endpoint's output channel will be used if available, and the REPLY_CHANNEL message header value
|
||||
will be used as a fallback.
|
||||
</para>
|
||||
<tip>
|
||||
The combination of output channels on endpoints and the reply channel message header enables a pipeline approach
|
||||
where multiple components have an output channel, and the final component simply allows the reply message to be
|
||||
forwarded to the reply channel as specified in the original request message. In other words, the final component
|
||||
depends on the information provided by the original sender and can dynamically support any number of clients as a
|
||||
result. This is an example of <ulink url="http://eaipatterns.com/ReturnAddress.html">Return Address</ulink>.
|
||||
</tip>
|
||||
<para>
|
||||
In addition to the examples shown here, these annotations also support inputChannel and outputChannel properties.
|
||||
<programlisting language="java">public class FooService {
|
||||
|
||||
@ServiceActivator(inputChannel="input", outputChannel="output")
|
||||
public void bar(String payload, @Headers Map<String, Object> headerMap) {
|
||||
...
|
||||
}
|
||||
|
||||
}</programlisting>
|
||||
That provides a pure annotation-driven alternative to the XML configuration. However, it is generally recommended
|
||||
to use XML for the endpoints, since it is easier to keep track of the overall configuration in a single, external
|
||||
location (and besides the namespace-based XML configuration is not very verbose). If you do prefer to provide
|
||||
channels with the annotations however, you just need to enable a SI Annotations BeanPostProcessor. The following element should
|
||||
be added: <programlisting language="xml"><![CDATA[ <int:annotation-config/> ]]></programlisting>
|
||||
<note>
|
||||
When configuring the "inputChannel" and "outputChannel" with annotations, the "inputChannel"
|
||||
<emphasis>must</emphasis> be a reference to a <interfacename>SubscribableChannel</interfacename> instance.
|
||||
Otherwise, it would be necessary to also provide the full poller configuration via annotations, and those
|
||||
settings (e.g. the trigger for scheduling the poller) should be externalized rather than hard-coded within
|
||||
an annotation. If the input channel that you want to receive Messages from is indeed a
|
||||
<interfacename>PollableChannel</interfacename> instance, one option to consider is the Messaging Bridge.
|
||||
Spring Integration's "bridge" element can be used to connect a PollableChannel directly to a
|
||||
SubscribableChannel. Then, the polling metadata is externally configured, but the annotation option is
|
||||
still available. For more detail see <xref linkend="bridge"/>.
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="message-mapping-rules">
|
||||
<title>Message Mapping rules and conventions</title>
|
||||
<para>Spring Integration implements a flexible facility to map Messages to Methods and their arguments without
|
||||
providing extra configuration by relying on some default rules as well as defining certain conventions.
|
||||
</para>
|
||||
<section id="sample-scenarios">
|
||||
<title>Simple Scenarios</title>
|
||||
|
||||
<para>
|
||||
<emphasis>Single un-annotated parameter (object or primitive) which is not a Map/Properties with non-void return type;</emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public String foo(Object o);</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>Input parameter is Message Payload. If parameter type is not compatible with Message Payload an
|
||||
attempt will be made to convert it using Conversion Service provided by Spring 3.0. The return value
|
||||
will be incorporated as a Payload of the returned Message</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Single un-annotated parameter (object or primitive) which is not a Map/Properties with Message return type;</emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public Message foo(Object o);</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>Input parameter is Message Payload. If parameter type is not compatible with Message Payload an attempt
|
||||
will be made to convert it using Conversion Service provided by Spring 3.0. The return value is a newly constructed
|
||||
Message that will be sent to the next destination.</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Single parameter which is a Message or its subclass with arbitrary object/primitive return type; </emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public int foo(Message msg);</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>Input parameter is Message itself. The return value will become a payload of the
|
||||
Message that will be sent to the next destination.</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Single parameter which is a Message or its subclass with Message or its subclass as a return type;</emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public Message foo(Message msg);</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>Input parameter is Message itself. The return value is a newly constructed Message that will be sent to the next destination.</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Single parameter which is of type Map or Properties with Message as a return type;</emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public Message foo(Map m);</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>This one is a bit interesting. Although at first it might seem like an easy mapping straight to Message Headers,
|
||||
the preference is always given to a Message Payload. This means that if Message Payload is of type Map, this input argument will
|
||||
represent Message Payload. However if Message Payload is not of type Map, then no conversion via Conversion Service will be
|
||||
attempted and the input argument will be mapped to Message Headers.</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Two parameters where one of them is arbitrary non-Map/Properties type object/primitive and another is Map/Properties type object (regardless of the return)</emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public Message foo(Map h, <T> t);</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>This combination contains two input parameters where one of them is of type Map. Naturally the non-Map parameters (regardless of the order) will
|
||||
be mapped to a Message Payload and the Map/Properties (regardless of the order) will be mapped to Message Headers giving you a nice POJO way
|
||||
of interacting with Message structure.</para>
|
||||
|
||||
<para>
|
||||
<emphasis>No parameters (regardless of the return)</emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public String foo();</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>This Message Handler method will be invoked based on the Message sent to the input channel this handler is hooked up to,
|
||||
however no Message data will be mapped, thus making Message act as event/trigger to invoke such handlerThe output will be
|
||||
mapped according to the rules above</para>
|
||||
|
||||
<para>
|
||||
<emphasis>No parameters, void return</emphasis>
|
||||
</para>
|
||||
<programlisting language="java">public void foo();</programlisting>
|
||||
<para>Details:</para>
|
||||
<para>Same as above, but no output </para>
|
||||
|
||||
<para>
|
||||
<emphasis>Annotation based mappings</emphasis>
|
||||
</para>
|
||||
<para>Annotation based mapping is the safest and least ambiguous approach to map Messages to Methods. There wil be many pointers to annotation
|
||||
based mapping throughout this manual, however here are couple of examples:
|
||||
</para>
|
||||
|
||||
<programlisting language="java">public String foo(@Payload String s, @Header("foo") String b) </programlisting>
|
||||
<para>Very simple and explicit way of mapping Messages to method. As you'll see later on, without an annotation this signature
|
||||
would result in an ambiguous condition. However by explicitly mapping the first argument to a Message Payload and the second argument to
|
||||
a value of the 'foo' Message Header, we have avoided any ambiguity.</para>
|
||||
|
||||
<programlisting language="java">public String foo(@Payload String s, @RequestParam("foo") String b) </programlisting>
|
||||
<para>Looks almost identical to the previous example, however @RequestMapping or any other non-Spring Integration mapping annotation
|
||||
is irrelevant and therefore will be ignored leaving the second parameter unmapped. Although the second parameter could
|
||||
easily be mapped to a Payload, there can only be one Payload. Therefore this method mapping is ambiguous.</para>
|
||||
|
||||
<programlisting language="java">public String foo(String s, @Header("foo") String b) </programlisting>
|
||||
<para>The same as above. The only difference is that the first argument will be mapped to the Message Payload implicitly.</para>
|
||||
|
||||
<programlisting language="java">public String foo(@Headers Map m, @Header("foo")Map f, @Header("bar") String bar)</programlisting>
|
||||
<para>Yet another signature that would definitely be treated as ambiguous without annotations because it has more than 2 arguments.
|
||||
Furthermore, two of them are Maps. However, with annotation-based mapping, the ambiguity is easily avoided. In this example
|
||||
the first argument is mapped to all the Message Headers, while the second and third argument map to the values of Message Headers
|
||||
'foo' and 'bar'. The payload is not being mapped to any argument.</para>
|
||||
</section>
|
||||
|
||||
<section id="complex-scenarios">
|
||||
<title>Complex Scenarios</title>
|
||||
|
||||
<para><emphasis>Multiple parameters:</emphasis> </para>
|
||||
<para>Multiple parameters could create a lot of ambiguity with regards to determining the appropriate mappings. The general advice is to annotate your method parameters with @Payload and/or @Header/@Headers
|
||||
Below are some of the examples of ambiguous conditions which result in an Exception being raised.
|
||||
</para>
|
||||
<programlisting language="java">public String foo(String s, int i)</programlisting>
|
||||
<para> - the two parameters are equal in weight, therefore there is no way to determine which one is a payload.</para>
|
||||
|
||||
<programlisting language="java">public String foo(String s, Map m, String b) </programlisting>
|
||||
<para> - almost the same as above. Although the Map could be easily mapped to Message Headers, there is no way to determine what to do with the two Strings.</para>
|
||||
|
||||
<programlisting language="java">public String foo(Map m, Map f)</programlisting>
|
||||
<para> - although one might argue that one Map could be mapped to Message Payload and another one to Message Headers, it would be unreasonable to rely on the order (e.g., first is Payload, second Headers)</para>
|
||||
|
||||
<para>
|
||||
<tip>Basically any method signature with more than one method argument which is not (Map, <T>), and those parameters are not annotated, will result in an ambiguous condition thus triggering an Exception.</tip>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Multiple methods:</emphasis>
|
||||
</para>
|
||||
<para>Message Handlers with multiple methods are mapped based on the same rules that are described above, however some scenarios might still look confusing.</para>
|
||||
|
||||
<para><emphasis>Multiple methods (same or different name) with legal (mappable) signatures:</emphasis> </para>
|
||||
|
||||
<programlisting language="java">public class Foo {
|
||||
public String foo(String str, Map m);
|
||||
|
||||
public String foo(Map m);
|
||||
}</programlisting>
|
||||
<para>As you can see, the Message could be mapped to either method. The first method would be invoked where Message Payload
|
||||
could be mapped to 'str' and Message Headers could be mapped to 'm'. The second method could easily also be a candidate where
|
||||
only Message Headers are mapped to 'm'. To make meters worse both methods have the same name which at first might look very
|
||||
ambiguous considering the following configuration:</para>
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="input" output-channel="output" method="foo">
|
||||
<bean class="org.bar.Foo"/>
|
||||
</int:service-activator>]]></programlisting>
|
||||
<para>At this point it would be important to understand Spring Integration mapping Conventions where at the very core,
|
||||
mappings are based on Payload first and everything else next. In other words the method whose argument could be mapped
|
||||
to a Payload will take precedence over all other methods.</para>
|
||||
|
||||
<para>On the other hand let's look at slightly different example:</para>
|
||||
<programlisting language="java">public class Foo {
|
||||
public String foo(String str, Map m);
|
||||
|
||||
public String foo(String str);
|
||||
}</programlisting>
|
||||
|
||||
<para>If you look at it you can probably see a truly ambiguous condition. In this example since both methods have signatures that
|
||||
could be mapped to a Message Payload. They also have the same name. Such handler methods will trigger an Exception.
|
||||
However if the method names were different you could influence the mapping with a 'method' attribute (see below):</para>
|
||||
<programlisting language="java">public class Foo {
|
||||
public String foo(String str, Map m);
|
||||
|
||||
public String bar(String str);
|
||||
}</programlisting>
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="input" output-channel="output" method="bar">
|
||||
<bean class="org.bar.Foo"/>
|
||||
</int:service-activator>]]></programlisting>
|
||||
|
||||
<para>Now there is no ambiguity since the configuration explicitly maps to the 'bar' method which has no name conflicts.</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
</appendix>
|
||||
455
src/reference/docbook/content-enrichment.xml
Normal file
@@ -0,0 +1,455 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="content-enricher"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Content Enricher</title>
|
||||
|
||||
<section id="content-enricher-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
At times you may have a requirement to enhance a request with more
|
||||
information than was provided by the target system. The
|
||||
<link href="http://www.eaipatterns.com/DataEnricher.html">Content Enricher</link>
|
||||
pattern describes various scenarios as well as the component
|
||||
(Enricher), which allows you to address such requirements.
|
||||
</para>
|
||||
<para>
|
||||
The Spring Integration <code>Core</code> module includes 2 enrichers:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem><link linkend='header-enricher'>Header Enricher</link></listitem>
|
||||
<listitem><link linkend='payload-enricher'>Payload Enricher</link></listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
Furthermore, several <emphasis>Adapter specific Header Enrichers</emphasis>
|
||||
are included as well:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem><link linkend='xml-xpath-header-enricher'>XPath Header Enricher (XML Module)</link></listitem>
|
||||
<listitem><link linkend='mail-namespace'>Mail Header Enricher (Mail Module)</link></listitem>
|
||||
<listitem><link linkend='xmpp-message-outbound-channel-adapter'>XMPP Header Enricher (XMPP Module)</link></listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
Please go to the adapter specific sections of this reference manual
|
||||
to learn more about those adapters.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="header-enricher">
|
||||
<title>Header Enricher</title>
|
||||
|
||||
<para>
|
||||
If you only need to add headers to a Message, and they are not
|
||||
dynamically determined by the Message content, then referencing a
|
||||
custom implementation of a Transformer may be overkill. For that reason,
|
||||
Spring Integration provides support for the <emphasis>Header Enricher</emphasis>
|
||||
pattern. It is exposed via the <code><header-enricher></code> element.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="in" output-channel="out">
|
||||
<int:header name="foo" value="123"/>
|
||||
<int:header name="bar" ref="someBean"/>
|
||||
</int:header-enricher>]]></programlisting>
|
||||
|
||||
<para>
|
||||
The <emphasis>Header Enricher</emphasis> also provides helpful sub-elements
|
||||
to set well-known header names.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="in" output-channel="out">
|
||||
<int:error-channel ref="applicationErrorChannel"/>
|
||||
<int:reply-channel ref="quoteReplyChannel"/>
|
||||
<int:correlation-id value="123"/>
|
||||
<int:priority value="HIGHEST"/>
|
||||
<int:header name="bar" ref="someBean"/>
|
||||
</int:header-enricher>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the above configuration you can clearly see that for well-known
|
||||
headers such as <code>errorChannel</code>, <code>correlationId</code>,
|
||||
<code>priority</code>, <code>replyChannel</code>etc., instead of
|
||||
using generic <emphasis><header></emphasis> sub-elements where
|
||||
you would have to provide both header 'name' and 'value', you can use
|
||||
convenient sub-elements to set those values directly.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>POJO Support</emphasis>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Often a header value cannot be defined statically and has to be
|
||||
determined dynamically based on some content in the Message. That is why
|
||||
<emphasis>Header Enricher</emphasis> allows you to also specify a bean
|
||||
reference using the <code>ref</code> and <code>method</code> attribute.
|
||||
The specified method will calculate the header value. Let's look at
|
||||
the following configuration:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="in" output-channel="out">
|
||||
<int:header name="foo" method="computeValue" ref="myBean"/>
|
||||
</int:header-enricher>
|
||||
|
||||
<bean id="myBean" class="foo.bar.MyBean"/>]]></programlisting>
|
||||
|
||||
<programlisting language="java"><![CDATA[public class MyBean {
|
||||
public String computeValue(String payload){
|
||||
return payload.toUpperCase() + "_US";
|
||||
}
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<para>
|
||||
You can also configure your POJO as inner bean:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="inputChannel" output-channel="outputChannel">
|
||||
<int:header name="some_header">
|
||||
<bean class="org.MyEnricher"/>
|
||||
</int:header>
|
||||
</int:header-enricher>]]></programlisting>
|
||||
<para>
|
||||
as well as point to a Groovy script:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="inputChannel" output-channel="outputChannel">
|
||||
<int:header name="some_header">
|
||||
<int-groovy:script location="org/SampleGroovyHeaderEnricher.groovy"/>
|
||||
</int:header>
|
||||
</int:header-enricher>]]></programlisting>
|
||||
|
||||
<para>
|
||||
<emphasis>SpEL Support</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
In Spring Integration 2.0 we have introduced the convenience of the
|
||||
<link href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html">Spring Expression Language (SpEL)</link>
|
||||
to help configure many different components. The <emphasis>Header
|
||||
Enricher</emphasis> is one of them.
|
||||
|
||||
Looking again at the POJO example above, you can see that the computation
|
||||
logic to determine the header value is actually pretty simple. A natural
|
||||
question would be: "is there a simpler way to accomplish this?". That
|
||||
is where SpEL shows its true power.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="in" output-channel="out">
|
||||
<int:header name="foo" expression="payload.toUpperCase() + '_US'"/>
|
||||
</int:header-enricher>]]></programlisting>
|
||||
|
||||
<para>
|
||||
As you can see, by using SpEL for such simple cases, we no longer have
|
||||
to provide a separate class and configure it in the application context.
|
||||
All we need is the <emphasis>expression</emphasis> attribute configured
|
||||
with a valid SpEL expression. The 'payload' and 'headers' variables
|
||||
are bound to the SpEL Evaluation Context, giving you full access to
|
||||
the incoming Message.
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="payload-enricher">
|
||||
<title>Payload Enricher</title>
|
||||
<para>
|
||||
In certain situations the Header Enricher, as discussed above, may
|
||||
not be sufficient and payloads themselves may have to be enriched
|
||||
with additional information. For example, order messages that enter
|
||||
the Spring Integration messaging system have to look up the order's
|
||||
customer based on the provided customer number and then enrich the original
|
||||
payload with that information.
|
||||
</para>
|
||||
<para>
|
||||
Since Spring Integration 2.1, the Payload Enricher is provided. A
|
||||
Payload Enricher defines an endpoint that passes a <interfacename>
|
||||
Message</interfacename> to the exposed request channel and then
|
||||
expects a reply message. The reply message then becomes the root object
|
||||
for evaluation of expressions to enrich the target payload.
|
||||
</para>
|
||||
<para>
|
||||
The Payload Enricher provides full XML namespace support via the <code>enricher</code>
|
||||
element. In order to send request messages, the payload enricher has a
|
||||
<code>request-channel</code> attribute that allows you to dispatch
|
||||
messages to a request channel.
|
||||
</para>
|
||||
<para>
|
||||
Basically by defining the request channel, the Payload Enricher acts
|
||||
as a Gateway, waiting for the message that were sent to the request
|
||||
channel to return, and the Enricher then augments the message's payload with
|
||||
the data provided by the reply message.
|
||||
</para>
|
||||
<para>
|
||||
When sending messages to the request channel you also have the option
|
||||
to only send a subset of the original payload using the
|
||||
<code>request-payload-expression</code> attribute.
|
||||
</para>
|
||||
<para>
|
||||
The enriching of payloads is configured through SpEL expressions,
|
||||
providing users with a maximum degree of flexibility. Therefore, users
|
||||
are not only able to enrich payloads with direct values from the reply channel's
|
||||
<interfacename>Message</interfacename>, but they can use SpEL
|
||||
expressions to extract a subset from that Message, only, or to apply
|
||||
addtional inline transformations, allowing them to further manipulate
|
||||
the data.
|
||||
</para>
|
||||
<para>
|
||||
If you only need to enrich payloads with static values, you don't have
|
||||
to provide the <code>request-channel</code> attribute.
|
||||
</para>
|
||||
<note>
|
||||
Enrichers are a variant of Transformers and in many cases you could
|
||||
use a Payload Enricher or a generic Transformer implementation to add
|
||||
additional data to your messages payloads. Thus, familiarize yourself
|
||||
with all transformation-capable components that are provided by Spring
|
||||
Integration and carefully select the implementation that semantically
|
||||
fits your business case best.
|
||||
</note>
|
||||
|
||||
<section id="payload-enricher-configuration">
|
||||
<title>Configuration</title>
|
||||
|
||||
<para>
|
||||
Below, please find an overview of all available configuration options that
|
||||
are available for the payload enricher:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:enricher request-channel="" ]]><co id="payload-enricher01-co" linkends="payload-enricher01" /><![CDATA[
|
||||
auto-startup="true" ]]><co id="payload-enricher02-co" linkends="payload-enricher02" /><![CDATA[
|
||||
id="" ]]><co id="payload-enricher03-co" linkends="payload-enricher03" /><![CDATA[
|
||||
order="" ]]><co id="payload-enricher04-co" linkends="payload-enricher04" /><![CDATA[
|
||||
output-channel="" ]]><co id="payload-enricher05-co" linkends="payload-enricher05" /><![CDATA[
|
||||
request-payload-expression="" ]]><co id="payload-enricher06-co" linkends="payload-enricher06" /><![CDATA[
|
||||
reply-channel="" ]]><co id="payload-enricher07-co" linkends="payload-enricher07" /><![CDATA[
|
||||
send-timeout="" ]]><co id="payload-enricher08-co" linkends="payload-enricher08" /><![CDATA[
|
||||
should-clone-payload="false"> ]]><co id="payload-enricher09-co" linkends="payload-enricher09" /><![CDATA[
|
||||
<int:poller></int:poller> ]]><co id="payload-enricher10-co" linkends="payload-enricher10" /><![CDATA[
|
||||
<int:property name="" expression=""/> ]]><co id="payload-enricher11-co" linkends="payload-enricher11" /><![CDATA[
|
||||
<int:property name="" value=""/>
|
||||
</int:enricher>]]></programlisting>
|
||||
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="payload-enricher01-co" id="payload-enricher01">
|
||||
<para>
|
||||
Channel to which a Message will be sent to get the data to use for enrichment.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher02-co" id="payload-enricher02">
|
||||
<para>
|
||||
Lifecycle attribute signaling if this component should be
|
||||
started during Application Context startup. Defaults to true.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher03-co" id="payload-enricher03">
|
||||
<para>
|
||||
Id of the underlying bean definition, which is either
|
||||
an <classname>EventDrivenConsumer</classname> or a
|
||||
<classname>PollingConsumer</classname>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher04-co" id="payload-enricher04">
|
||||
<para>
|
||||
Specifies the order for invocation when this endpoint is
|
||||
connected as a subscriber to a channel. This is particularly
|
||||
relevant when that channel is using a "failover" dispatching
|
||||
strategy. It has no effect when this endpoint itself is a
|
||||
Polling Consumer for a channel with a queue.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher05-co" id="payload-enricher05">
|
||||
<para>
|
||||
Identifies the Message channel where a Message will
|
||||
be sent after it is being processed by this endpoint.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher06-co" id="payload-enricher06">
|
||||
<para>
|
||||
By default the original message's payload will be used as
|
||||
payload that will be send to the <code>request-channel</code>.
|
||||
By specifying a SpEL expression as value for the
|
||||
<code>request-payload-expression</code> attribute, a
|
||||
subset of the original payload, a header value or any other
|
||||
resolvable SpEL expression can be used as the basis for the
|
||||
payload, that will be sent to the request-channel.
|
||||
</para>
|
||||
<para>
|
||||
For the Expression evaluation the full message is available
|
||||
as the 'root object'.
|
||||
</para>
|
||||
<para>
|
||||
For instance the following SpEL expressions (among others)
|
||||
are possible:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>payload.foo</listitem>
|
||||
<listitem>headers.foobar</listitem>
|
||||
<listitem>new java.util.Date()</listitem>
|
||||
<listitem>'foo' + 'bar'</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
If more sophisticated logic is required (e.g. changing the
|
||||
message headers etc.) please use additional downstream transformers.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher07-co" id="payload-enricher07">
|
||||
<para>
|
||||
Channel where a reply Message is expected. This is optional; typically the auto-generated
|
||||
temporary reply channel is sufficient.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher08-co" id="payload-enricher08">
|
||||
<para>
|
||||
Maximum amount of time in milliseconds to wait when
|
||||
sending a message to the channel, if such channel may block.
|
||||
</para>
|
||||
<para>
|
||||
For example, a Queue Channel can block until space is
|
||||
available, if its maximum capacity has been reached. Internally
|
||||
the send timeout is set on the <classname>MessagingTemplate</classname>
|
||||
and ultimately applied when invoking the send operation on the
|
||||
<interfacename>MessageChannel</interfacename>.
|
||||
</para>
|
||||
<para>
|
||||
By default the send timeout is set to '-1', which may cause
|
||||
the send operation on the <interfacename>MessageChannel</interfacename>,
|
||||
depending on the implementation, to block indefinitely.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher09-co" id="payload-enricher09">
|
||||
<para>
|
||||
Boolean value indicating whether any payload that implements
|
||||
<interfacename>Cloneable</interfacename> should be cloned
|
||||
prior to sending the Message to the request chanenl for
|
||||
acquiring the enriching data. The cloned version would be
|
||||
used as the target payload for the ultimate reply.
|
||||
Default is <code>false</code>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher10-co" id="payload-enricher10">
|
||||
<para>
|
||||
Allows you to configure a Message Poller if this endpoint
|
||||
is a Polling Consumer.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="payload-enricher11-co" id="payload-enricher11">
|
||||
<para>
|
||||
Each <code>property</code> sub-element provides the
|
||||
name of a property (via the mandatory <code>name</code>
|
||||
attribute). That property should be settable on the
|
||||
target payload instance. Exactly one of the <code>value</code>
|
||||
or <code>expression</code> attributes must be provided
|
||||
as well. The former for a literal value to set, and the
|
||||
latter for a SpEL expression to be evaluated. The root
|
||||
object of the evaluation context is the Message that was
|
||||
returned from the flow initiated by this enricher.
|
||||
</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="payload-enricher-examples">
|
||||
<title>Examples</title>
|
||||
|
||||
<para>
|
||||
Below, please find several examples of using a Payload Enricher
|
||||
in various situations.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
In the following example, a <classname>User</classname> object is passed
|
||||
as the payload of the <interfacename>Message</interfacename>. The
|
||||
<classname>User</classname> has several properties but only the
|
||||
<code>username</code> is set initially. The Enricher's
|
||||
<code>request-channel</code> attribute below is configured to
|
||||
pass the <classname>User</classname> on to the <code>findUserServiceChannel</code>.
|
||||
</para>
|
||||
<para>
|
||||
Through the implicitly set <code>reply-channel</code> a
|
||||
<classname>User</classname> object is returned and using the
|
||||
<code>property</code> sub-element, properties from the reply are
|
||||
extracted and used to enrich the original payload.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:enricher id="findUserEnricher"
|
||||
input-channel="findUserEnricherChannel"
|
||||
request-channel="findUserServiceChannel">
|
||||
<int:property name="email" expression="payload.email"/>
|
||||
<int:property name="password" expression="payload.password"/>
|
||||
</int:enricher>]]></programlisting>
|
||||
|
||||
<note>
|
||||
The code samples shown here, are part of the <emphasis>Spring
|
||||
Integration Samples</emphasis> project. Please feel free to
|
||||
check it out at:
|
||||
|
||||
<ulink url="https://github.com/SpringSource/spring-integration-samples"/>
|
||||
|
||||
</note>
|
||||
|
||||
<para><emphasis>How do I pass only a subset of data to the request channel?</emphasis></para>
|
||||
<para>
|
||||
Using a <code>request-payload-expression</code> attribute
|
||||
a single property of the payload can be passed on to the request
|
||||
channel instead of the full message. In the example below on the
|
||||
username property is passed on to the request channel. Keep in mind,
|
||||
that alwhough only the username is passed on, the resulting message
|
||||
send to the request channel will contain the full set of
|
||||
<classname>MessageHeaders</classname>.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:enricher id="findUserByUsernameEnricher"
|
||||
input-channel="findUserByUsernameEnricherChannel"
|
||||
request-channel="findUserByUsernameServiceChannel"
|
||||
request-payload-expression="payload.username">
|
||||
<int:property name="email" expression="payload.email"/>
|
||||
<int:property name="password" expression="payload.password"/>
|
||||
</int:enricher>]]></programlisting>
|
||||
|
||||
<para><emphasis>How can I enrich payloads that consist of Collection data?</emphasis></para>
|
||||
<para>
|
||||
In the following example, instead of a <classname>User</classname> object,
|
||||
a <interfacename>Map</interfacename> is passed in. The
|
||||
<interfacename>Map</interfacename> contains the username under the map
|
||||
key <code>username</code>. Only the <code>username</code> is passed on
|
||||
to the request channel. The reply contains a full <classname>User</classname> object, which
|
||||
is ultimately added to the <interfacename>Map</interfacename> under the
|
||||
<code>user</code> key.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:enricher id="findUserWithMapEnricher"
|
||||
input-channel="findUserWithMapEnricherChannel"
|
||||
request-channel="findUserByUsernameServiceChannel"
|
||||
request-payload-expression="payload.username">
|
||||
<int:property name="user" expression="payload"/>
|
||||
</int:enricher>]]></programlisting>
|
||||
|
||||
<para><emphasis>How can I enrich payloads with static information without using a request channel?</emphasis></para>
|
||||
<para>
|
||||
Here is an example that does not use a request channel at all,
|
||||
but solely enriches the message's payload with static values. But please
|
||||
be aware that the word 'static' is used loosly here. You can still use
|
||||
SpEL expressions for setting those values.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:enricher id="userEnricher"
|
||||
input-channel="input">
|
||||
<int:property name="user.updateDate" expression="new java.util.Date()"/>
|
||||
<int:property name="user.firstName" value="foo"/>
|
||||
<int:property name="user.lastName" value="bar"/>
|
||||
<int:property name="user.age" value="42"/>
|
||||
</int:enricher>]]></programlisting>
|
||||
|
||||
</section>
|
||||
|
||||
</section>
|
||||
</section>
|
||||
48
src/reference/docbook/control-bus.xml
Normal file
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section version="5.0" xml:id="control-bus"
|
||||
xmlns="http://docbook.org/ns/docbook"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:ns5="http://www.w3.org/1999/xhtml"
|
||||
xmlns:ns4="http://www.w3.org/1998/Math/MathML"
|
||||
xmlns:ns3="http://www.w3.org/2000/svg"
|
||||
xmlns:ns="http://docbook.org/ns/docbook">
|
||||
<title>Control Bus</title>
|
||||
|
||||
<para>As described in (EIP), the idea behind the Control Bus is that the
|
||||
same messaging system can be used for monitoring and managing the components
|
||||
within the framework as is used for "application-level" messaging. In Spring
|
||||
Integration we build upon the adapters described above so that it's possible
|
||||
to send Messages as a means of invoking exposed operations.</para>
|
||||
|
||||
<programlisting language="xml"><int:control-bus input-channel="operationChannel"/></programlisting>
|
||||
|
||||
<para>The Control Bus has an input channel that can be accessed for invoking
|
||||
operations on the beans in the application context. It also has all the
|
||||
common properties of a service activating endpoint, e.g. you can specify an
|
||||
output channel if the result of the operation has a return value that you
|
||||
want to send on to a downstream channel.</para>
|
||||
|
||||
<para>The Control Bus executes messages on the input channel as Spring
|
||||
Expression Language expressions. It takes a message, compiles the body to an
|
||||
expression, adds some context, and then executes it. The default context
|
||||
supports any method that has been annotated with @ManagedAttribute or @ManagedOperation.
|
||||
It also supports the methods on Spring's Lifecycle interface, and it supports methods
|
||||
that are used to configure several of Spring's TaskExecutor and TaskScheduler implementations.
|
||||
The simplest way to ensure that your own methods are available to the Control Bus is to
|
||||
use the @ManagedAttribute and/or @ManagedOperation annotations. Since those are also used
|
||||
for exposing methods to a JMX MBean registry, it's a convenient by-product (often the same
|
||||
types of operations you want to expose to the Control Bus would be reasonable for exposing
|
||||
via JMS). Resolution of any particular instance within the application context is achieved
|
||||
in the typical SpEL syntax. Simply provide the bean name with the SpEL prefix for beans (@).
|
||||
For example, to execute a method on a Spring Bean a client
|
||||
could send a message to the operation channel as follows:</para>
|
||||
|
||||
<programlisting>Message operation = MessageBuilder.withPayload("@myServiceBean.shutdown()").build();
|
||||
operationChannel.send(operation)</programlisting>
|
||||
|
||||
<para>The root of the context for the expression is the
|
||||
<classname>Message</classname> itself, so you also have access to the 'payload'
|
||||
and 'headers' as variables within your expression. This is consistent with all the other expression
|
||||
support in Spring Integration endpoints.</para>
|
||||
|
||||
</section>
|
||||
61
src/reference/docbook/delayer.xml
Normal file
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="delayer"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Delayer</title>
|
||||
|
||||
<section id="delayer-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
A Delayer is a simple endpoint that allows a Message flow to be delayed by a certain interval. When
|
||||
a Message is delayed, the original sender will not block. Instead, the delayed Messages will be
|
||||
scheduled with an instance of <interfacename>java.util.concurrent.ScheduledExecutorService</interfacename>
|
||||
to be sent to the output channel after the delay has passed. This approach is scalable even for
|
||||
rather long delays, since it does not result in a large number of blocked sender Threads. On the
|
||||
contrary, in the typical case a thread pool will be used for the actual execution of releasing the
|
||||
Messages. Below you will find several examples of configuring a Delayer.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="delayer-namespace">
|
||||
<title>Configuring Delayer</title>
|
||||
<para>
|
||||
The <delayer> element is used to delay the Message flow between two Message Channels.
|
||||
As with the other endpoints, you can provide the "input-channel" and "output-channel" attributes,
|
||||
but the delayer also requires at least the 'default-delay' attribute with the number of milliseconds
|
||||
that each Message should be delayed.
|
||||
<programlisting language="xml"><![CDATA[ <int:delayer input-channel="input" default-delay="3000" output-channel="output"/>]]></programlisting>
|
||||
If you need per-Message determination of the delay, then you can also provide the name of a header
|
||||
within the 'delay-header-name' attribute:
|
||||
<programlisting language="xml"><![CDATA[ <int:delayer input-channel="input" output-channel="output"
|
||||
default-delay="3000" delay-header-name="delay"/>]]></programlisting>
|
||||
In the example above the 3 second delay would only apply in the case that the header value is
|
||||
not present for a given inbound Message. If you only want to apply a delay to Messages that have
|
||||
an explicit header value, then you can set the 'default-delay' to 0. For any Message that has a
|
||||
delay of 0 (or less), the Message will be sent directly. In fact, if there is not a positive delay
|
||||
value for a Message, it will be sent to the output channel on the calling Thread.
|
||||
<tip>
|
||||
The delay handler actually supports header values that represent an interval in milliseconds (any
|
||||
Object whose <methodname>toString()</methodname> method produces a value that can be parsed into a
|
||||
Long) as well as <classname>java.util.Date</classname> instances representing an absolute time.
|
||||
In the former case, the milliseconds will be counted from the current time (e.g. a value of 5000
|
||||
would delay the Message for at least 5 seconds from the time it is received by the Delayer). In
|
||||
the latter case, with an actual Date instance, the Message will not be released until that Date
|
||||
occurs. In either case, a value that equates to a non-positive delay, or a Date in the past, will
|
||||
not result in any delay. Instead, it will be sent directly to the output channel in the original
|
||||
sender's Thread.
|
||||
</tip>
|
||||
</para>
|
||||
<para>
|
||||
The delayer delegates to an instance of Spring's <interfacename>TaskScheduler</interfacename> abstraction.
|
||||
The default scheduler used by the delayer is a <classname>ThreadPoolTaskScheduler</classname> instance with a pool size of 1.
|
||||
If you want to delegate to a different scheduler, you can provide a reference through the delayer element's
|
||||
'scheduler' attribute:
|
||||
<programlisting language="xml"><![CDATA[ <int:delayer input-channel="input" output-channel="output"
|
||||
default-delay="0" delay-header-name="delay"
|
||||
scheduler="exampleTaskScheduler"/>
|
||||
|
||||
<task:scheduler id="exampleTaskScheduler" pool-size="3"/>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
356
src/reference/docbook/endpoint.xml
Normal file
@@ -0,0 +1,356 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="endpoint"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Endpoints</title>
|
||||
<para>
|
||||
The first part of this chapter covers some background theory and reveals quite a bit about the underlying API
|
||||
that drives Spring Integration's various messaging components. This information can be helpful if you want to
|
||||
really understand what's going on behind the scenes. However, if you want to get up and running with the
|
||||
simplified namespace-based configuration of the various elements, feel free to skip ahead to
|
||||
<xref linkend="endpoint-namespace"/> for now.
|
||||
</para>
|
||||
<para>
|
||||
As mentioned in the overview, Message Endpoints are responsible for connecting the various messaging components to
|
||||
channels. Over the next several chapters, you will see a number of different components that consume Messages. Some
|
||||
of these are also capable of sending reply Messages. Sending Messages is quite straightforward. As shown above in
|
||||
<xref linkend="channel"/>, it's easy to <emphasis>send</emphasis> a Message to a Message Channel. However,
|
||||
receiving is a bit more complicated. The main reason is that there are two types of consumers:
|
||||
<ulink url="http://www.eaipatterns.com/PollingConsumer.html">Polling Consumers</ulink> and
|
||||
<ulink url="http://www.eaipatterns.com/EventDrivenConsumer.html">Event Driven Consumers</ulink>.
|
||||
</para>
|
||||
<para>
|
||||
Of the two, Event Driven Consumers are much simpler. Without any need to manage and schedule a separate poller
|
||||
thread, they are essentially just listeners with a callback method. When connecting to one of Spring Integration's
|
||||
subscribable Message Channels, this simple option works great. However, when connecting to a buffering, pollable
|
||||
Message Channel, some component has to schedule and manage the polling thread(s). Spring Integration provides
|
||||
two different endpoint implementations to accommodate these two types of consumers. Therefore, the consumers
|
||||
themselves can simply implement the callback interface. When polling is required, the endpoint acts as a
|
||||
"container" for the consumer instance. The benefit is similar to that of using a container for hosting
|
||||
Message Driven Beans, but since these consumers are simply Spring-managed Objects running within an
|
||||
ApplicationContext, it more closely resembles Spring's own MessageListener containers.
|
||||
</para>
|
||||
|
||||
<section id="endpoint-handler">
|
||||
<title>Message Handler</title>
|
||||
<para>
|
||||
Spring Integration's <interfacename>MessageHandler</interfacename> interface is implemented by many of the
|
||||
components within the framework. In other words, this is not part of the public API, and a developer would not
|
||||
typically implement <interfacename>MessageHandler</interfacename> directly. Nevertheless, it is used by a Message
|
||||
Consumer for actually handling the consumed Messages, and so being aware of this strategy interface does help in
|
||||
terms of understanding the overall role of a consumer. The interface is defined as follows:
|
||||
<programlisting language="java">public interface MessageHandler {
|
||||
|
||||
void handleMessage(Message<?> message);
|
||||
|
||||
}</programlisting>
|
||||
Despite its simplicity, this provides the foundation for most of the components that will be covered in the
|
||||
following chapters (Routers, Transformers, Splitters, Aggregators, Service Activators, etc). Those components
|
||||
each perform very different functionality with the Messages they handle, but the requirements for actually
|
||||
receiving a Message are the same, and the choice between polling and event-driven behavior is also the same.
|
||||
Spring Integration provides two endpoint implementations that "host" these callback-based handlers and allow
|
||||
them to be connected to Message Channels.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="endpoint-eventdrivenconsumer">
|
||||
<title>Event Driven Consumer</title>
|
||||
<para>
|
||||
Because it is the simpler of the two, we will cover the Event Driven Consumer endpoint first. You may recall that
|
||||
the <interfacename>SubscribableChannel</interfacename> interface provides a <methodname>subscribe()</methodname>
|
||||
method and that the method accepts a <interfacename>MessageHandler</interfacename> parameter (as shown in
|
||||
<xref linkend="channel-interfaces-subscribablechannel"/>):
|
||||
<programlisting language="java">
|
||||
subscribableChannel.subscribe(messageHandler);
|
||||
</programlisting>
|
||||
Since a handler that is subscribed to a channel does not have to actively poll that channel, this is an
|
||||
Event Driven Consumer, and the implementation provided by Spring Integration accepts a
|
||||
a <interfacename>SubscribableChannel</interfacename> and a <interfacename>MessageHandler</interfacename>:
|
||||
<programlisting language="java">SubscribableChannel channel = context.getBean("subscribableChannel", SubscribableChannel.class);
|
||||
|
||||
EventDrivenConsumer consumer = new EventDrivenConsumer(channel, exampleHandler);</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="endpoint-pollingconsumer">
|
||||
<title>Polling Consumer</title>
|
||||
<para>
|
||||
Spring Integration also provides a <classname>PollingConsumer</classname>, and it can be instantiated in
|
||||
the same way except that the channel must implement <interfacename>PollableChannel</interfacename>:
|
||||
<programlisting language="java">PollableChannel channel = context.getBean("pollableChannel", PollableChannel.class);
|
||||
|
||||
PollingConsumer consumer = new PollingConsumer(channel, exampleHandler);</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
There are many other configuration options for the Polling Consumer. For example, the trigger is a required property:
|
||||
<programlisting language="java">
|
||||
PollingConsumer consumer = new PollingConsumer(channel, handler);
|
||||
|
||||
consumer.setTrigger(new IntervalTrigger(30, TimeUnit.SECONDS));</programlisting>
|
||||
Spring Integration currently provides two implementations of the <interfacename>Trigger</interfacename>
|
||||
interface: <classname>IntervalTrigger</classname> and <classname>CronTrigger</classname>. The
|
||||
<classname>IntervalTrigger</classname> is typically defined with a simple interval (in milliseconds), but
|
||||
also supports an 'initialDelay' property and a boolean 'fixedRate' property (the default is false, i.e.
|
||||
fixed delay):
|
||||
<programlisting language="java">IntervalTrigger trigger = new IntervalTrigger(1000);
|
||||
trigger.setInitialDelay(5000);
|
||||
trigger.setFixedRate(true);</programlisting>
|
||||
The <classname>CronTrigger</classname> simply requires a valid cron expression (see the Javadoc for details):
|
||||
<programlisting language="java">CronTrigger trigger = new CronTrigger("*/10 * * * * MON-FRI");</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
In addition to the trigger, several other polling-related configuration properties may be specified:
|
||||
<programlisting language="java">
|
||||
PollingConsumer consumer = new PollingConsumer(channel, handler);
|
||||
|
||||
consumer.setMaxMessagesPerPoll(10);
|
||||
|
||||
consumer.setReceiveTimeout(5000);</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The 'maxMessagesPerPoll' property specifies the maximum number of messages to receive within a given poll
|
||||
operation. This means that the poller will continue calling receive() <emphasis>without waiting</emphasis>
|
||||
until either <code>null</code> is returned or that max is reached. For example, if a poller has a 10 second
|
||||
interval trigger and a 'maxMessagesPerPoll' setting of 25, and it is polling a channel that has 100 messages
|
||||
in its queue, all 100 messages can be retrieved within 40 seconds. It grabs 25, waits 10 seconds, grabs the
|
||||
next 25, and so on.
|
||||
</para>
|
||||
<para>
|
||||
The 'receiveTimeout' property specifies the amount of time the poller should wait if no messages are
|
||||
available when it invokes the receive operation. For example, consider two options that seem similar on
|
||||
the surface but are actually quite different: the first has an interval trigger of 5 seconds and a receive
|
||||
timeout of 50 milliseconds while the second has an interval trigger of 50 milliseconds and a receive timeout
|
||||
of 5 seconds. The first one may receive a message up to 4950 milliseconds later than it arrived on the channel
|
||||
(if that message arrived immediately after one of its poll calls returned). On the other hand, the second
|
||||
configuration will never miss a message by more than 50 milliseconds. The difference is that the second
|
||||
option requires a thread to wait, but as a result it is able to respond much more quickly to arriving messages.
|
||||
This technique, known as "long polling", can be used to emulate event-driven behavior on a polled source.
|
||||
</para>
|
||||
<para>
|
||||
A Polling Consumer may also delegate to a Spring <interfacename>TaskExecutor</interfacename>, and it can
|
||||
be configured to participate in Spring-managed transactions. The following example shows the configuration of both:
|
||||
<programlisting language="java">
|
||||
PollingConsumer consumer = new PollingConsumer(channel, handler);
|
||||
|
||||
TaskExecutor taskExecutor = context.getBean("exampleExecutor", TaskExecutor.class);
|
||||
consumer.setTaskExecutor(taskExecutor);
|
||||
|
||||
PlatformTransactionManager txManager = context.getBean("exampleTxManager", PlatformTransationManager.class);
|
||||
consumer.setTransactionManager(txManager);</programlisting>
|
||||
The examples above show dependency lookups, but keep in mind that these consumers will most often be configured
|
||||
as Spring <emphasis>bean definitions</emphasis>. In fact, Spring Integration also provides a
|
||||
<interfacename>FactoryBean</interfacename> that creates the appropriate consumer type based on the type of
|
||||
channel, and there is full XML namespace support to even further hide those details. The namespace-based
|
||||
configuration will be featured as each component type is introduced.
|
||||
<note>
|
||||
Many of the <interfacename>MessageHandler</interfacename> implementations are also capable of generating reply
|
||||
Messages. As mentioned above, sending Messages is trivial when compared to the Message reception. Nevertheless,
|
||||
<emphasis>when</emphasis> and <emphasis>how many</emphasis> reply Messages are sent depends on the handler
|
||||
type. For example, an <emphasis>Aggregator</emphasis> waits for a number of Messages to arrive and is often
|
||||
configured as a downstream consumer for a <emphasis>Splitter</emphasis> which may generate multiple
|
||||
replies for each Message it handles. When using the namespace configuration, you do not strictly need to know
|
||||
all of the details, but it still might be worth knowing that several of these components share a common base
|
||||
class, the <classname>AbstractReplyProducingMessageHandler</classname>, and it provides a
|
||||
<methodname>setOutputChannel(..)</methodname> method.
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="endpoint-namespace">
|
||||
<title>Namespace Support</title>
|
||||
<para>
|
||||
Throughout the reference manual, you will see specific configuration examples for endpoint elements, such as
|
||||
router, transformer, service-activator, and so on. Most of these will support an "input-channel" attribute and
|
||||
many will support an "output-channel" attribute. After being parsed, these endpoint elements produce an instance
|
||||
of either the <classname>PollingConsumer</classname> or the
|
||||
<classname>EventDrivenConsumer</classname> depending on the type of the "input-channel" that is
|
||||
referenced: <interfacename>PollableChannel</interfacename> or <interfacename>SubscribableChannel</interfacename>
|
||||
respectively. When the channel is pollable, then the polling behavior is determined based on the endpoint
|
||||
element's "poller" sub-element and its attributes. For example, a simple interval-based poller with a 1-second interval would be
|
||||
configured like this: <programlisting language="xml"><![CDATA[ <int:transformer input-channel="pollable"
|
||||
ref="transformer"
|
||||
output-channel="output">
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int:transformer>]]></programlisting>
|
||||
As an alternative to 'fixed-rate' you can also use the 'fixed-delay' attribute.
|
||||
</para>
|
||||
<para>
|
||||
For a poller based on a Cron expression, use the "cron" attribute instead:
|
||||
<programlisting language="xml"><![CDATA[ <int:transformer input-channel="pollable"
|
||||
ref="transformer"
|
||||
output-channel="output">
|
||||
<int:poller cron="*/10 * * * * MON-FRI"/>
|
||||
</int:transformer>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
If the input channel is a <interfacename>PollableChannel</interfacename>, then the poller configuration is
|
||||
required. Specifically, as mentioned above, the 'trigger' is a required property of the PollingConsumer class.
|
||||
Therefore, if you omit the "poller" sub-element for a Polling Consumer endpoint's configuration, an Exception
|
||||
may be thrown. The exception will also be thrown if you attempt to configure a poller on the element that is
|
||||
connected to a non-pollable channel.
|
||||
</para>
|
||||
<para>
|
||||
It is also possible to create top-level pollers in which case only a "ref" is required:
|
||||
<programlisting language="xml"><![CDATA[ <int:poller id="weekdayPoller" cron="*/10 * * * * MON-FRI"/>
|
||||
|
||||
<int:transformer input-channel="pollable"
|
||||
ref="transformer"
|
||||
output-channel="output">
|
||||
<int:poller ref="weekdayPoller"/>
|
||||
</int:transformer>]]></programlisting>
|
||||
<note>
|
||||
The "ref" attribute is only allowed on the inner-poller definitions. Defining this attribute on a top-level
|
||||
poller will result in a configuration exception thrown during initialization of the Application Context.
|
||||
</note>
|
||||
In fact, to simplify the configuration even further, you can define a global default poller. A single top-level poller within
|
||||
an ApplicationContext may have the <code>default</code> attribute with a value of "true". In that case, any
|
||||
endpoint with a PollableChannel for its input-channel that is defined within the same ApplicationContext and has
|
||||
no explicitly configured 'poller' sub-element will use that default.
|
||||
<programlisting language="xml"><![CDATA[ <int:poller id="defaultPoller" default="true" max-messages-per-poll="5" fixed-rate="3000"/>
|
||||
|
||||
<!-- No <poller/> sub-element is necessary since there is a default -->
|
||||
<int:transformer input-channel="pollable"
|
||||
ref="transformer"
|
||||
output-channel="output"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Spring Integration also provides transaction support for the pollers so that each receive-and-forward
|
||||
operation can be performed as an atomic unit-of-work. To configure transactions for a poller, simply add the
|
||||
<transactional/> sub-element. The attributes for this element should be familiar to anyone who has
|
||||
experience with Spring's Transaction management:
|
||||
<programlisting language="xml"><![CDATA[<int:poller fixed-delay="1000">
|
||||
<int:transactional transaction-manager="txManager"
|
||||
propagation="REQUIRED"
|
||||
isolation="REPEATABLE_READ"
|
||||
timeout="10000"
|
||||
read-only="false"/>
|
||||
</int:poller>]]></programlisting>
|
||||
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>AOP Advice chains</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
Since Spring transaction support depends on the Proxy mechanism with <classname>TransactionInterceptor</classname> (AOP Advice) handling transactional
|
||||
behavior of the message flow initiated by the poler, some times there is a need to provide extra Advice(s) to handle other
|
||||
cross cutting behavior associated with the poller. For that poller defines an 'advice-chain' element allowing you to add
|
||||
more advices - class that implements <classname>MethodInterceptor</classname> interface..
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator id="advicedSa" input-channel="goodInputWithAdvice" ref="testBean"
|
||||
method="good" output-channel="output">
|
||||
<int:poller max-messages-per-poll="1" fixed-rate="10000">
|
||||
<int:transactional transaction-manager="txManager" />
|
||||
<int:advice-chain>
|
||||
<ref bean="adviceA" />
|
||||
<beans:bean class="org.bar.SampleAdvice"/>
|
||||
</int:advice-chain>
|
||||
</int:poller>
|
||||
</int:service-activator>]]></programlisting>
|
||||
For more information on how to implement MethodInterceptor please refer to AOP sections of Spring
|
||||
reference manual (section 7 and 8). Advice chain can also be applied on the poller that does not have
|
||||
any transaction configuration essentially allowing you to enhance the behavior of the message flow initiated by the poller.
|
||||
</para>
|
||||
<para>
|
||||
The polling threads may be executed by any instance of Spring's <interfacename>TaskExecutor</interfacename>
|
||||
abstraction. This enables concurrency for an endpoint or group of endpoints. As of Spring 3.0, there is a "task"
|
||||
namespace in the core Spring Framework, and its <executor/> element supports the creation of a simple thread
|
||||
pool executor. That element accepts attributes for common concurrency settings such as pool-size and queue-capacity.
|
||||
Configuring a thread-pooling executor can make a substantial difference in how the endpoint performs under load. These
|
||||
settings are available per-endpoint since the performance of an endpoint is one of the major factors to consider
|
||||
(the other major factor being the expected volume on the channel to which the endpoint subscribes). To enable
|
||||
concurrency for a polling endpoint that is configured with the XML namespace support, provide the 'task-executor'
|
||||
reference on its <poller/> element and then provide one or more of the properties shown below:
|
||||
<programlisting language="xml"><![CDATA[ <int:poller task-executor="pool" fixed-rate="1000"/>
|
||||
|
||||
<task:executor id="pool"
|
||||
pool-size="5-25"
|
||||
queue-capacity="20"
|
||||
keep-alive="120"/>]]></programlisting>
|
||||
If no 'task-executor' is provided, the consumer's handler will be invoked in the caller's thread. Note that the
|
||||
"caller" is usually the default <interfacename>TaskScheduler</interfacename>
|
||||
(see <xref linkend="namespace-taskscheduler"/>). Also, keep in mind that the 'task-executor' attribute can
|
||||
provide a reference to any implementation of Spring's <interfacename>TaskExecutor</interfacename> interface by
|
||||
specifying the bean name. The "executor" element above is simply provided for convenience.
|
||||
</para>
|
||||
<para>
|
||||
As mentioned in the background section for Polling Consumers above, you can also configure a Polling Consumer
|
||||
in such a way as to emulate event-driven behavior. With a long receive-timeout and a short interval-trigger,
|
||||
you can ensure a very timely reaction to arriving messages even on a polled message source. Note that this
|
||||
will only apply to sources that have a blocking wait call with a timeout. For example, the File poller does
|
||||
not block, each receive() call returns immediately and either contains new files or not. Therefore, even if
|
||||
a poller contains a long receive-timeout, that value would never be usable in such a scenario. On the other
|
||||
hand when using Spring Integration's own queue-based channels, the timeout value does have a chance to
|
||||
participate. The following example demonstrates how a Polling Consumer will receive Messages nearly
|
||||
instantaneously.
|
||||
<programlisting language="xml"><![CDATA[ <int:service-activator input-channel="someQueueChannel"
|
||||
output-channel="output">
|
||||
<int:poller receive-timeout="30000" fixed-rate="10"/>
|
||||
|
||||
</int:service-activator>]]></programlisting>
|
||||
Using this approach does not carry much overhead since internally it is nothing more then a timed-wait thread
|
||||
which does not require nearly as much CPU resource usage as a thrashing, infinite while loop for example.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="payload-type-conversion">
|
||||
<title>Payload Type Conversion</title>
|
||||
<para>
|
||||
Throughout the reference manual, you will also see specific configuration and implementation examples of various endpoints
|
||||
which can accept a Message or any arbitrary Object as an input parameter. In the case of an Object, such a parameter will
|
||||
be mapped to a Message payload or part of the payload or header (when using the Spring Expression Language). However there
|
||||
are times when the type of input parameter of the endpoint method does not match the type of the payload or its part.
|
||||
In this scenario we need to perform type conversion. Spring Integration provides a convenient way for registering type
|
||||
converters (using the Spring 3.x ConversionService) within its own instance of a conversion service bean named <emphasis>integrationConversionService</emphasis>.
|
||||
That bean is automatically created as soon as the first converter is defined using the Spring Integration namespace support.
|
||||
|
||||
To register a Converter all you need is to implement
|
||||
<interfacename>org.springframework.core.convert.converter.Converter</interfacename> and define it via
|
||||
convenient namespace support:
|
||||
<programlisting language="xml"><![CDATA[ <int:converter ref="sampleConverter"/>
|
||||
|
||||
<bean id="sampleConverter" class="foo.bar.TestConverter"/>]]></programlisting>
|
||||
|
||||
or as an inner bean:
|
||||
<programlisting language="xml"><![CDATA[ <int:converter>
|
||||
<bean class="org.springframework.integration.config.xml.ConverterParserTests$TestConverter3"/>
|
||||
</int:converter>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="async-polling">
|
||||
<title>Asynchronous polling</title>
|
||||
<para>
|
||||
If you want the polling to be asynchronous, a Poller can optionally specify a 'task-executor' attribute
|
||||
pointing to an existing instance of any <classname>TaskExecutor</classname> bean
|
||||
(Spring 3.0 provides a convenient namespace configuration via the <code>task</code> namespace). However, there are certain things
|
||||
you must understand when configuring a Poller with a TaskExecutor.
|
||||
</para>
|
||||
<para>
|
||||
The problem is that there are two configurations in place. The <emphasis>Poller</emphasis> and the <emphasis>TaskExecutor</emphasis>,
|
||||
and they both have to be in tune with each other otherwise you might end up creating an artificial memory leak.
|
||||
</para>
|
||||
<para>
|
||||
Let's look at the following configuration provided by one of the users on the Spring Integration
|
||||
forum (http://forum.springsource.org/showthread.php?t=94519):
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="publishChannel" ref="myService">
|
||||
<int:poller receive-timeout="5000" task-executor="taskExecutor" fixed-rate="50"/>
|
||||
</int:service-activator>
|
||||
|
||||
<task:executor id="taskExecutor" pool-size="20" queue-capacity="20"/>]]></programlisting>
|
||||
|
||||
The above configuration demonstrates one of those out of tune configurations.
|
||||
</para>
|
||||
<para>
|
||||
The poller keeps scheduling new tasks even though all the threads are blocked waiting for either a new message to arrive,
|
||||
or the timeout to expire. Given that there are 20 threads executing tasks with a 5 second timeout, they will be executed
|
||||
at a rate of 4 per second (5000/20 = 250ms). But, new tasks are being scheduled at a rate of 20 per second, so the internal
|
||||
queue in the task executor will grow at a rate of 16 per second (while the process is idle), so we essentially have a memory leak.
|
||||
</para>
|
||||
<para>
|
||||
One of the ways to handle this is to set the <code>queue-capacity</code> attribute of the Task Executor to 0. You can also
|
||||
manage it by specifying what to do with messages that can not be queued by setting the <code>rejection-policy</code> attribute
|
||||
of the Task Executor (e.g., DISCARD). In other words there are certain details you must understand with regard to configuring
|
||||
the TaskExecutor. Please refer to - <emphasis>Section 25 - Task Execution and Scheduling</emphasis> of the Spring reference manual
|
||||
for more detail on the subject.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
77
src/reference/docbook/event.xml
Normal file
@@ -0,0 +1,77 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="applicationevent"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
|
||||
<title>Spring ApplicationEvent Support</title>
|
||||
|
||||
<para>
|
||||
Spring Integration provides support for inbound and outbound <classname>ApplicationEvents</classname>
|
||||
as defined by the underlying Spring Framework. For more information about Spring's support for events and listeners,
|
||||
refer to the <ulink url="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#context-functionality-events">Spring Reference Manual</ulink>.
|
||||
</para>
|
||||
|
||||
<section id="applicationevent-inbound">
|
||||
<title>Receiving Spring ApplicationEvents</title>
|
||||
<para>
|
||||
To receive events and send them to a channel, simply define an instance of Spring Integration's
|
||||
<classname>ApplicationEventListeningMessageProducer</classname>. This class is an implementation of
|
||||
Spring's <interfacename>ApplicationListener</interfacename> interface. By default it will pass all
|
||||
received events as Spring Integration Messages. To limit based on the type of event, configure the
|
||||
list of event types that you want to receive with the 'eventTypes' property. If a received event
|
||||
has a Message instance as its 'source', then that will be passed as-is. Otherwise, if a SpEL-based
|
||||
"payloadExpression" has been provided, that will be evaluated against the ApplicationEvent instance.
|
||||
If the event's source is not a Message instance and no "payloadExpression" has been provided, then
|
||||
the ApplicationEvent itself will be passed as the payload.
|
||||
</para>
|
||||
<para>
|
||||
For convenience namespace support is provided to configure an <classname>ApplicationEventListeningMessageProducer</classname>
|
||||
via the <emphasis>inbound-channel-adapter</emphasis> element.
|
||||
<programlisting language="xml"><![CDATA[<int-event:inbound-channel-adapter channel="eventChannel"
|
||||
error-channel="eventErrorChannel"
|
||||
event-types="example.FooEvent, example.BarEvent"/>
|
||||
|
||||
<int:publish-subscribe-channel id="eventChannel"/>]]></programlisting>
|
||||
In the above example, all Application Context events that match one of the types specified by the 'event-types' (optional) attribute will be
|
||||
delivered as Spring Integration Messages to the Message Channel named 'eventChannel'. If a downstream component throws
|
||||
an exception, a MessagingException containing the failed message and exception will be sent to the channel named
|
||||
'eventErrorChannel'. If no "error-channel" is specified and the downstream channels are synchronous, the Exception
|
||||
will be propagated to the caller.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="applicationevent-outbound">
|
||||
<title>Sending Spring ApplicationEvents</title>
|
||||
<para>
|
||||
To send Spring <classname>ApplicationEvents</classname>, create an instance of the
|
||||
<classname>ApplicationEventPublishingMessageHandler</classname> and register it within an endpoint.
|
||||
This implementation of the <interfacename>MessageHandler</interfacename> interface also implements
|
||||
Spring's <interfacename>ApplicationEventPublisherAware</interfacename> interface and thus acts as a
|
||||
bridge between Spring Integration Messages and <classname>ApplicationEvents</classname>.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
For convenience namespace support is provided to configure an <classname>ApplicationEventPublishingMessageHandler</classname>
|
||||
via the <emphasis>outbound-channel-adapter</emphasis> element.
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="eventChannel"/>
|
||||
|
||||
<int-event:outbound-channel-adapter channel="eventChannel"/>]]></programlisting>
|
||||
If you are using a PollableChannel (e.g., Queue), you can also provide <emphasis>poller</emphasis> as a sub-element of the
|
||||
<emphasis>outbound-channel-adapter</emphasis> element. You can also optionally provide a <emphasis>task-executor</emphasis>
|
||||
reference for that poller. The following example demonstrates both.
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="eventChannel">
|
||||
<int:queue/>
|
||||
</int:channel>
|
||||
|
||||
<int-event:outbound-channel-adapter channel="eventChannel">
|
||||
<int:poller max-messages-per-poll="1" task-executor="executor" fixed-rate="100"/>
|
||||
</int-event:outbound-channel-adapter>
|
||||
|
||||
<task:executor id="executor" pool-size="5"/>]]></programlisting>
|
||||
|
||||
In the above example, all messages sent to the 'eventChannel' channel will be published as ApplicationEvents to any relevant
|
||||
ApplicationListener instances that are registered within the same Spring ApplicationContext. If the payload of the Message is
|
||||
an ApplicationEvent, it will be passed as-is. Otherwise the Message itself will be wrapped in a MessagingEvent instance.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
83
src/reference/docbook/feed.xml
Normal file
@@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="feed"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Feed Adapter</title>
|
||||
<para>
|
||||
Spring Integration provides support for Syndication via Feed Adapters
|
||||
</para>
|
||||
<section id="feed-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
Web syndication is a form of publishing material such as news stories, press releases, blog posts, and
|
||||
other items typically available on a website but also made available in a feed format such as RSS or ATOM.
|
||||
</para>
|
||||
<para>
|
||||
Spring integration provides support for Web Syndication via its 'feed' adapter and provides convenient
|
||||
namespace-based configuration for it.
|
||||
To configure the 'feed' namespace, include the following elements within the headers of your XML configuration file:
|
||||
|
||||
<programlisting language="xml"><![CDATA[xmlns:int-feed="http://www.springframework.org/schema/integration/feed"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration/feed
|
||||
http://www.springframework.org/schema/integration/feed/spring-integration-feed.xsd"]]></programlisting>
|
||||
|
||||
</para>
|
||||
</section>
|
||||
<section>
|
||||
<title>Feed Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The only adapter that is really needed to provide support for retrieving feeds is an <emphasis>inbound channel adapter</emphasis>.
|
||||
This allows you to subscribe to a particular URL. Below is an example configuration:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-feed:inbound-channel-adapter id="feedAdapter"
|
||||
channel="feedChannel"
|
||||
url="http://feeds.bbci.co.uk/news/rss.xml">
|
||||
<int:poller fixed-rate="10000" max-messages-per-poll="100" />
|
||||
</int-feed:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
In the above configuration, we are subscribing to a URL identified by the <code>url</code> attribute.
|
||||
</para>
|
||||
<para>
|
||||
As news items are retrieved they will be converted to Messages and sent to a channel identified by the <code>channel</code> attribute.
|
||||
The payload of each message will be a <classname>com.sun.syndication.feed.synd.SyndEntry</classname> instance. That encapsulates
|
||||
various data about a news item (content, dates, authors, etc.).
|
||||
</para>
|
||||
<para>
|
||||
You can also see that the <emphasis>Inbound Feed Channel Adapter</emphasis> is a Polling Consumer. That means you have to
|
||||
provide a poller configuration. However, one important thing you must understand with regard to Feeds is that its inner-workings
|
||||
are slightly different then most other poling consumers. When an Inbound Feed adapter is started, it does the first poll and
|
||||
receives a <classname>com.sun.syndication.feed.synd.SyndEntryFeed</classname> instance. That is an object that contains multiple
|
||||
<classname>SyndEntry</classname> objects. Each entry is stored in the local entry queue and is released based on
|
||||
the value in the <code>max-messages-per-poll</code> attribute such that each Message will contain a single entry.
|
||||
If during retrieval of the entries from the entry queue the queue had become empty, the adapter will attempt to update
|
||||
the Feed thereby populating the queue with more entries (SyndEntry instances) if available. Otherwise the next attempt to
|
||||
poll for a feed will be determined by the trigger of the poller (e.g., every 10 seconds in the above configuration).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Duplicate Entries</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
Polling for a Feed might result in entries that have already been processed
|
||||
("I already read that news item, why are you showing it to me again?").
|
||||
Spring Integration provides a convenient mechanism to eliminate the need to worry about duplicate entries.
|
||||
Each feed entry will have a <emphasis>published date</emphasis> field. Every time a new Message is generated and sent,
|
||||
Spring Integration will store the value of the latest <emphasis>published date</emphasis> in an instance of the
|
||||
<classname>org.springframework.integration.store.MetadataStore</classname> strategy. The MetadataStore interface is
|
||||
designed to store various types of generic meta-data (e.g., published date of the last feed entry that has been processed)
|
||||
to help components such as this Feed adapter deal with duplicates.
|
||||
</para>
|
||||
<para>
|
||||
The default rule for locating this metadata store is as follows: Spring Integration will look for a bean of type
|
||||
<classname>org.springframework.integration.store.MetadataStore</classname> in the ApplicationContext. If one is found then it will be used,
|
||||
otherwise it will create a new instance of <classname>SimpleMetadataStore</classname> which is an in-memory implementation that
|
||||
will only persist metadata within the lifecycle of the currently running Application Context. This means that upon restart you may
|
||||
end up with duplicate entries. If you need to persist metadata between Application Context restarts, you may use the
|
||||
<classname>PropertiesPersistingMetadataStore</classname> which is backed by a properties file and a properties-persister.
|
||||
Alternatively, you could provide your own implementation of the <classname>MetadataStore</classname> interface
|
||||
(e.g. JdbcMetadataStore) and configure it as bean in the Application Context.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<bean id="metadataStore"
|
||||
class="org.springframework.integration.store.PropertiesPersistingMetadataStore"/>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
</chapter>
|
||||
248
src/reference/docbook/file.xml
Normal file
@@ -0,0 +1,248 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="files"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>File Support</title>
|
||||
|
||||
<section id="file-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
Spring Integration's File support extends the Spring Integration Core with
|
||||
a dedicated vocabulary to deal with reading, writing, and transforming files.
|
||||
It provides a namespace that enables elements defining Channel Adapters dedicated
|
||||
to files and support for Transformers that can read file contents into strings or
|
||||
byte arrays.
|
||||
</para>
|
||||
<para>
|
||||
This section will explain the workings of <classname>FileReadingMessageSource</classname>
|
||||
and <classname>FileWritingMessageHandler</classname> and how to configure them as
|
||||
<emphasis>beans</emphasis>. Also the support for dealing with files through file specific
|
||||
implementations of <interfacename>Transformer</interfacename> will be discussed. Finally the
|
||||
file specific namespace will be explained.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="file-reading">
|
||||
<title>Reading Files</title>
|
||||
<para>
|
||||
A <classname>FileReadingMessageSource</classname> can be used to consume files from the filesystem.
|
||||
This is an implementation of <interfacename>MessageSource</interfacename> that creates messages from
|
||||
a file system directory. <programlisting language="xml"><![CDATA[<bean id="pollableFileSource"
|
||||
class="org.springframework.integration.file.FileReadingMessageSource"
|
||||
p:inputDirectory="${input.directory}"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To prevent creating messages for certain files, you may supply a
|
||||
<interfacename>FileListFilter</interfacename>. By default, an
|
||||
<classname>AcceptOnceFileListFilter</classname> is used. This filter
|
||||
ensures files are picked up only once from the directory.
|
||||
<programlisting language="xml"><![CDATA[<bean id="pollableFileSource"
|
||||
class="org.springframework.integration.file.FileReadingMessageSource"
|
||||
p:inputDirectory="${input.directory}"
|
||||
p:filter-ref="customFilterBean"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
A common problem with reading files is that a file may be detected before
|
||||
it is ready. The default <classname>AcceptOnceFileListFilter</classname>
|
||||
does not prevent this. In most cases, this can be prevented if the
|
||||
file-writing process renames each file as soon as it is ready for
|
||||
reading. A filename-pattern or filename-regex filter that accepts only files that are
|
||||
ready (e.g. based on a known suffix), composed with the default
|
||||
<classname>AcceptOnceFileListFilter</classname> allows for this.
|
||||
The <classname>CompositeFileListFilter</classname> enables the
|
||||
composition.
|
||||
<programlisting language="xml"><![CDATA[<bean id="pollableFileSource"
|
||||
class="org.springframework.integration.file.FileReadingMessageSource"
|
||||
p:inputDirectory="${input.directory}"
|
||||
p:filter-ref="compositeFilter"/>
|
||||
<bean id="compositeFilter"
|
||||
class="org.springframework.integration.file.filters.CompositeFileListFilter">
|
||||
<constructor-arg>
|
||||
<list>
|
||||
<bean class="org.springframework.integration.file.filters.AcceptOnceFileListFilter"/>
|
||||
<bean class="org.springframework.integration.file.filters.RegexPatternFileListFilter">
|
||||
<constructor-arg value="^test.*$"/>
|
||||
</bean>
|
||||
</list>
|
||||
</constructor-arg>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The configuration can be simplified using the file specific namespace. To do
|
||||
this use the following template.
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:int="http://www.springframework.org/schema/integration"
|
||||
xmlns:int-file="http://www.springframework.org/schema/integration/file"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd
|
||||
http://www.springframework.org/schema/integration/file
|
||||
http://www.springframework.org/schema/integration/file/spring-integration-file.xsd">
|
||||
</beans>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Within this namespace you can reduce the FileReadingMessageSource and wrap
|
||||
it in an inbound Channel Adapter like this:
|
||||
<programlisting language="xml"><![CDATA[ <int-file:inbound-channel-adapter id="filesIn1"
|
||||
directory="file:${input.directory}" prevent-duplicates="true"/>
|
||||
|
||||
<int-file:inbound-channel-adapter id="filesIn2"
|
||||
directory="file:${input.directory}"
|
||||
filter="customFilterBean" />
|
||||
|
||||
<int-file:inbound-channel-adapter id="filesIn3"
|
||||
directory="file:${input.directory}"
|
||||
filename-pattern="test*" />
|
||||
|
||||
<int-file:inbound-channel-adapter id="filesIn4"
|
||||
directory="file:${input.directory}"
|
||||
filename-regex="test[0-9]+\.txt" /> ]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The first channel adapter is relying on the default filter that just prevents
|
||||
duplication, the second is using a custom filter, the third is using the
|
||||
<emphasis>filename-pattern</emphasis> attribute to add an <classname>AntPathMatcher</classname>
|
||||
based filter, and the fourth is using the <emphasis>filename-regex</emphasis> attribute to add a
|
||||
regular expression Pattern based filter to the <classname>FileReadingMessageSource</classname>.
|
||||
The <emphasis>filename-pattern</emphasis> and <emphasis>filename-regex</emphasis> attributes are
|
||||
each mutually exclusive with the regular <emphasis>filter</emphasis> reference attribute. However,
|
||||
you can use the <emphasis>filter</emphasis> attribute to reference an instance of
|
||||
<classname>CompositeFileListFilter</classname> that combines any number of filters, including one
|
||||
or more pattern based filters to fit your particular needs.
|
||||
</para>
|
||||
<para>
|
||||
When multiple processes are reading from the same directory it can be desirable to lock files to prevent
|
||||
them from being picked up concurrently. To do this you can use a <interfacename>FileLocker</interfacename>.
|
||||
There is a java.nio based implementation available out of the box, but it is also possible to implement your
|
||||
own locking scheme. The nio locker can be injected as follows
|
||||
<programlisting language="xml"><![CDATA[ <int-file:inbound-channel-adapter id="filesIn"
|
||||
directory="file:${input.directory}" prevent-duplicates="true">
|
||||
<int-file:nio-locker/>
|
||||
</int-file:inbound-channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
A custom locker you can configure like this:
|
||||
<programlisting language="xml"><![CDATA[ <int-file:inbound-channel-adapter id="filesIn"
|
||||
directory="file:${input.directory}" prevent-duplicates="true">
|
||||
<int-file:locker ref="customLocker"/>
|
||||
</int-file:inbound-channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
When a file inbound adapter is configured with a locker, it will take the responsibility to acquire a
|
||||
lock before the file is allowed to be received.
|
||||
<emphasis role="bold">It will not assume the responsibility to unlock the file.</emphasis>
|
||||
If you have processed the file and keeping the locks hanging around you have a memory leak. If this is
|
||||
a problem in your case you should call FileLocker.unlock(File file) yourself at the appropriate time.
|
||||
</note>
|
||||
<para>
|
||||
When filtering and locking files is not enough it might be needed to control the way files are listed entirely. To
|
||||
implement this type of requirement you can use an implementation of <interfacename>DirectoryScanner</interfacename>.
|
||||
This scanner allows you to determine entirely what files are listed each poll. This is also the interface
|
||||
that Spring Integration uses internally to wire FileListFilters FileLocker to the FileReadingMessageSource.
|
||||
A custom DirectoryScanner can be injected into the <int-file:inbound-channel-adapter/> on the <code>scanner</code>
|
||||
attribute.
|
||||
<programlisting language="xml"><![CDATA[ <int-file:inbound-channel-adapter id="filesIn" directory="file:${input.directory}"
|
||||
prevent-duplicates="true" scanner="customDirectoryScanner"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
This gives you full freedom to choose the ordering, listing and locking strategies.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="file-writing">
|
||||
<title>Writing files</title>
|
||||
<para>
|
||||
To write messages to the file system you can use a
|
||||
<classname>FileWritingMessageHandler</classname>. This class can deal with
|
||||
File, String, or byte array payloads. In its simplest form the
|
||||
<classname>FileWritingMessageHandler </classname> only requires a
|
||||
destination directory for writing the files. The name of the file to be
|
||||
written is determined by the handler's <classname>FileNameGenerator</classname>.
|
||||
The default implementation looks for a Message header whose key matches
|
||||
the constant defined as <code>FileHeaders.FILENAME</code>.
|
||||
</para>
|
||||
<para>
|
||||
Additionally, you can configure the encoding and the charset that
|
||||
will be used in case of a String payload.
|
||||
</para>
|
||||
<para>
|
||||
To make things easier you can configure the FileWritingMessageHandler as
|
||||
part of an outbound channel adapter using the namespace.
|
||||
<programlisting language="xml"><![CDATA[ <int-file:outbound-channel-adapter id="filesOut" directory="${input.directory.property}"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The namespace based configuration also supports a <code>delete-source-files</code> attribute.
|
||||
If set to <code>true</code>, it will trigger deletion of the original source files after writing
|
||||
to a destination. The default value for that flag is <code>false</code>.
|
||||
<programlisting language="xml"><![CDATA[ <int-file:outbound-channel-adapter id="filesOut"
|
||||
directory="${output.directory}"
|
||||
delete-source-files="true"/>]]></programlisting>
|
||||
<note>
|
||||
The <code>delete-source-files</code> attribute will only have an effect if the inbound
|
||||
Message has a File payload or if the <classname>FileHeaders.ORIGINAL_FILE</classname> header
|
||||
value contains either the source File instance or a String representing the original file path.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
In cases where you want to continue processing messages based on the written File you can use
|
||||
the <code>outbound-gateway</code> instead. It plays a very similar role as the
|
||||
<code>outbound-channel-adapter</code>. However after writing the File, it will also send it
|
||||
to the reply channel as the payload of a Message.
|
||||
<programlisting language="xml"><![CDATA[ <int-file:outbound-gateway id="mover" request-channel="moveInput"
|
||||
reply-channel="output"
|
||||
directory="${output.directory}"
|
||||
delete-source-files="true"/>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
The 'outbound-gateway' works well in cases where you want to first move a file and then send it
|
||||
through a processing pipeline. In such cases, you may connect the file namespace's
|
||||
'inbound-channel-adapter' element to the 'outbound-gateway' and then connect that gateway's
|
||||
reply-channel to the beginning of the pipeline.
|
||||
</note>
|
||||
<para>
|
||||
If you have more elaborate requirements or need to support additional payload types as input
|
||||
to be converted to file content you could extend the FileWritingMessageHandler, but a much
|
||||
better option is to rely on a <classname>Transformer</classname>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="file-transforming">
|
||||
<title>File Transformers</title>
|
||||
<para>
|
||||
To transform data read from the file system to objects and the other way around you need
|
||||
to do some work. Contrary to <classname>FileReadingMessageSource</classname> and to a
|
||||
lesser extent <classname>FileWritingMessageHandler</classname>, it is very likely that you
|
||||
will need your own mechanism to get the job done. For this you can implement the
|
||||
<interfacename>Transformer</interfacename> interface. Or extend the
|
||||
<classname>AbstractFilePayloadTransformer</classname> for inbound messages. Some obvious
|
||||
implementations have been provided.
|
||||
</para>
|
||||
<para>
|
||||
<classname>FileToByteArrayTransformer</classname> transforms Files into byte[]s using
|
||||
Spring's <classname>FileCopyUtils</classname>. It is often better to use a sequence of
|
||||
transformers than to put all transformations in a single class. In that case the File to
|
||||
byte[] conversion might be a logical first step.
|
||||
</para>
|
||||
<para>
|
||||
<classname>FileToStringTransformer</classname> will convert Files to Strings as the name
|
||||
suggests. If nothing else, this can be useful for debugging (consider using with a Wire Tap).
|
||||
</para>
|
||||
<para>
|
||||
To configure File specific transformers you can use the appropriate elements from the file namespace.
|
||||
<programlisting language="xml"><![CDATA[ <int-file:file-to-bytes-transformer input-channel="input" output-channel="output"
|
||||
delete-files="true"/>
|
||||
|
||||
<int-file:file-to-string-transformer input-channel="input" output-channel="output"
|
||||
delete-files="true" charset="UTF-8"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The <emphasis>delete-files</emphasis> option signals to the transformer that it should delete
|
||||
the inbound File after the transformation is complete. This is in no way a replacement for using the
|
||||
<classname>AcceptOnceFileListFilter</classname> when the FileReadingMessageSource is being used in a
|
||||
multi-threaded environment (e.g. Spring Integration in general).
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
171
src/reference/docbook/filter.xml
Normal file
@@ -0,0 +1,171 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="filter"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Filter</title>
|
||||
|
||||
<section id="filter-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
Message Filters are used to decide whether a Message should be passed along or dropped based on some criteria
|
||||
such as a Message Header value or Message content itself. Therefore, a Message Filter is similar
|
||||
to a router, except that for each Message received from the filter's input channel, that same Message may or may
|
||||
not be sent to the filter's output channel. Unlike the router, it makes no decision regarding
|
||||
<emphasis>which</emphasis> Message Channel to send the Message to but only decides <emphasis>whether</emphasis> to send.
|
||||
<note>
|
||||
As you will see momentarily, the Filter also supports a discard channel, so in certain cases it
|
||||
<emphasis>can</emphasis> play the role of a very simple router (or "switch") based on a boolean condition.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
In Spring Integration, a Message Filter may be configured as a Message Endpoint that delegates to an
|
||||
implementation of the <interfacename>MessageSelector</interfacename> interface. That interface is itself quite
|
||||
simple: <programlisting language="java"><![CDATA[ public interface MessageSelector {
|
||||
|
||||
boolean accept(Message<?> message);
|
||||
|
||||
}]]></programlisting>
|
||||
The <classname>MessageFilter</classname> constructor accepts a selector instance:
|
||||
<programlisting language="java"><![CDATA[ MessageFilter filter = new MessageFilter(someSelector);]]></programlisting>
|
||||
</para>
|
||||
In combination with the namespace and SpEL, very powerful filters can be configured with very little java code.
|
||||
</section>
|
||||
|
||||
<section id="filter-config">
|
||||
<title>Configuring Filter</title>
|
||||
<section id="filter-xml">
|
||||
<title>Configuring a Filter with XML</title>
|
||||
|
||||
<para>
|
||||
The <filter> element is used to create a Message-selecting endpoint. In addition to "<code>input-channel</code>
|
||||
and <code>output-channel</code> attributes, it requires a <code>ref</code>. The <code>ref</code> may point to a
|
||||
<interfacename>MessageSelector</interfacename> implementation:
|
||||
<programlisting language="xml"><![CDATA[ <int:filter input-channel="input" ref="selector" output-channel="output"/>
|
||||
|
||||
<bean id="selector" class="example.MessageSelectorImpl"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Alternatively, the <code>method</code> attribute can be added at which point the <code>ref</code> may refer to any object.
|
||||
The referenced method may expect either the <interfacename>Message</interfacename> type or the payload type of
|
||||
inbound Messages. The method must return a boolean value. If the method returns 'true',
|
||||
the Message <emphasis>will</emphasis> be sent to the output-channel.
|
||||
<programlisting language="xml"><![CDATA[ <int:filter input-channel="input" output-channel="output"
|
||||
ref="exampleObject" method="someBooleanReturningMethod"/>
|
||||
|
||||
<bean id="exampleObject" class="example.SomeObject"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
If the selector or adapted POJO method returns <code>false</code>, there are a few settings that control the
|
||||
handling of the rejected Message. By default (if configured like the example above), rejected Messages will
|
||||
be silently dropped. If rejection should instead result in an error condition, then set the
|
||||
<code>throw-exception-on-rejection</code> attribute to <code>true</code>:
|
||||
<programlisting language="xml"><![CDATA[ <int:filter input-channel="input" ref="selector"
|
||||
output-channel="output" throw-exception-on-rejection="true"/> ]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
If you want rejected messages to be routed to a specific channel, provide that reference as the <code>discard-channel</code>:
|
||||
<programlisting language="xml"><![CDATA[ <int:filter input-channel="input" ref="selector"
|
||||
output-channel="output" discard-channel="rejectedMessages"/> ]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
Message Filters are commonly used in conjunction with a Publish Subscribe Channel. Many filter endpoints may
|
||||
be subscribed to the same channel, and they decide whether or not to pass the Message to the next endpoint which
|
||||
could be any of the supported types (e.g. Service Activator). This provides a <emphasis>reactive</emphasis>
|
||||
alternative to the more <emphasis>proactive</emphasis> approach of using a Message Router with a single
|
||||
Point-to-Point input channel and multiple output channels.
|
||||
</note>
|
||||
<para>
|
||||
Using a <code>ref</code> attribute is generally recommended if the custom filter implementation is referenced in other
|
||||
<code><filter></code> definitions. However if the custom filter implementation is scoped to a
|
||||
single <code><filter></code> element, provide an inner bean definition:
|
||||
<programlisting language="xml"><![CDATA[<int:filter method="someMethod" input-channel="inChannel" output-channel="outChannel">
|
||||
<beans:bean class="org.foo.MyCustomFilter"/>
|
||||
</filter>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
Using both the <code>ref</code> attribute and an inner handler definition in the same <code><filter></code> configuration
|
||||
is not allowed, as it creates an ambiguous condition, and an Exception will be thrown.
|
||||
</para>
|
||||
</note>
|
||||
<para>
|
||||
With the introduction of SpEL support, Spring Integration added the <code>expression</code> attribute to the filter
|
||||
element. It can be used to avoid Java entirely for simple filters.
|
||||
<programlisting language="xml"><![CDATA[<int:filter input-channel="input" expression="payload.equals('nonsense')"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The string passed as the expression attribute will be evaluated as a SpEL expression with the Message available in
|
||||
the evaluation context.
|
||||
If it is necessary to include the result of an expression in the scope of the application context you can use the
|
||||
#{} notation as defined in the
|
||||
<ulink url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html#expressions-beandef">
|
||||
SpEL reference documentation
|
||||
</ulink>.
|
||||
<programlisting language="xml"><![CDATA[<int:filter input-channel="input"
|
||||
expression="payload.matches(#{filterPatterns.nonsensePattern})"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
If the Expression itself needs to be dynamic, then an 'expression' sub-element may be used. That provides a level of
|
||||
indirection for resolving the Expression by its key from an ExpressionSource. That is a strategy interface that you
|
||||
can implement directly, or you can rely upon a version available in Spring Integration that loads Expressions from
|
||||
a "resource bundle" and can check for modifications after a given number of seconds. All of this is demonstrated in
|
||||
the following configuration sample where the Expression could be reloaded within one minute if the underlying file
|
||||
had been modified. If the ExpressionSource bean is named "expressionSource", then it is not necessary to provide the
|
||||
<code>source</code> attribute on the <expression> element, but in this case it's shown for completeness.
|
||||
<programlisting language="xml"><![CDATA[<int:filter input-channel="input" output-channel="output">
|
||||
<int:expression key="filterPatterns.example" source="myExpressions"/>
|
||||
</int:filter>
|
||||
|
||||
<beans:bean id="myExpressions" id="myExpressions"
|
||||
class="org.springframework.integration.expression.ReloadableResourceBundleExpressionSource">
|
||||
<beans:property name="basename" value="config/integration/expressions"/>
|
||||
<beans:property name="cacheSeconds" value="60"/>
|
||||
</beans:bean>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Then, the 'config/integration/expressions.properties' file (or any more specific version with a locale extension
|
||||
to be resolved in the typical way that resource-bundles are loaded) would contain a key/value pair:
|
||||
<programlisting language="xml"><![CDATA[ filterPatterns.example=payload > 100]]></programlisting>
|
||||
|
||||
<note>All of these examples that use <code>expression</code> as an attribute
|
||||
or sub-element can also be applied within transformer, router, splitter,
|
||||
service-activator, and header-enricher elements. Of course, the semantics/role
|
||||
of the given component type would affect the interpretation of the evaluation
|
||||
result in the same way that the return value of a method-invocation would
|
||||
be interpreted. For example, an expression can return Strings that are to
|
||||
be treated as Message Channel names by a router component. However, the
|
||||
underlying functionality of evaluating the expression against the Message
|
||||
as the root object, and resolving bean names if prefixed with '@' is consistent
|
||||
across all of the core EIP components within Spring Integration.</note>
|
||||
</para>
|
||||
</section>
|
||||
<section id="filter-annotations">
|
||||
<title>Configuring a Filter with Annotations</title>
|
||||
<para>A filter configured using annotations would look like this.</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[public class PetFilter {
|
||||
...
|
||||
|
||||
@Filter ]]><co id="filterann" /><![CDATA[
|
||||
public boolean dogsOnly(String input) {
|
||||
...
|
||||
}
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<calloutlist>
|
||||
<callout arearefs="filterann">
|
||||
<para>An annotation indicating that this method shall be used as a
|
||||
filter. Must be specified if this class will be used as a filter.</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
|
||||
<para>All of the configuration options provided by the xml element are
|
||||
also available for the <interfacename>@Filter</interfacename> annotation.</para>
|
||||
|
||||
<para>The filter can be either referenced explicitly from XML or, if
|
||||
the <interfacename>@MessageEndpoint</interfacename> annotation is defined
|
||||
on the class, detected automatically through classpath scanning.</para>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
379
src/reference/docbook/ftp.xml
Normal file
@@ -0,0 +1,379 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="ftp"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>FTP/FTPS Adapters</title>
|
||||
<para>
|
||||
Spring Integration provides support for file transfer operations via FTP and FTPS.
|
||||
</para>
|
||||
<section id="ftp-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
The File Transfer Protocol (FTP) is a simple network protocol which allows you to transfer files between two computers on the Internet.
|
||||
</para>
|
||||
<para>
|
||||
There are two actors when it comes to FTP communication: <emphasis>client</emphasis> and <emphasis>server</emphasis>.
|
||||
To transfer files with FTP/FTPS, you use a <emphasis>client</emphasis> which initiates a connection to a remote computer
|
||||
that is running an FTP <emphasis>server</emphasis>. After the connection is established, the <emphasis>client</emphasis> can choose
|
||||
to send and/or receive copies of files.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration supports sending and receiving files over FTP/FTPS by providing three <emphasis>client</emphasis>
|
||||
side endpoints: <emphasis>Inbound Channel Adapter</emphasis>, <emphasis>Outbound Channel Adapter</emphasis>, and
|
||||
<emphasis>Outbound Gateway</emphasis>. It also provides
|
||||
convenient namespace-based configuration options for defining these <emphasis>client</emphasis> components.
|
||||
</para>
|
||||
<para>
|
||||
To use the <emphasis>FTP</emphasis> namespace, add the following to the header of your XML file:
|
||||
<programlisting language="xml"><![CDATA[xmlns:int-ftp="http://www.springframework.org/schema/integration/ftp"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration/ftp
|
||||
http://www.springframework.org/schema/integration/ftp/spring-integration-ftp.xsd"
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
|
||||
<section id="ftp-session-factory">
|
||||
<title>FTP Session Factory</title>
|
||||
<para>
|
||||
Before configuring FTP adapters you must configure an <emphasis>FTP Session Factory</emphasis>. You can configure
|
||||
the <emphasis>FTP Session Factory</emphasis> with a regular bean definition where the implementation class is <classname>org.springframework.integration.ftp.session.DefaultFtpSessionFactory</classname>:
|
||||
Below is a basic configuration:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<bean id="ftpClientFactory"
|
||||
class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
|
||||
<property name="host" value="localhost"/>
|
||||
<property name="port" value="22"/>
|
||||
<property name="username" value="kermit"/>
|
||||
<property name="password" value="frog"/>
|
||||
<property name="clientMode" value="0"/>
|
||||
<property name="fileType" value="2"/>
|
||||
<property name="bufferSize" value="100000"/>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
For FTPS connections all you need to do is use <classname>org.springframework.integration.ftp.session.DefaultFtpsSessionFactory</classname> instead.
|
||||
Below is the complete configuration sample:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<bean id="ftpClientFactory"
|
||||
class="org.springframework.integration.ftp.client.DefaultFtpsClientFactory">
|
||||
<property name="host" value="localhost"/>
|
||||
<property name="port" value="22"/>
|
||||
<property name="username" value="oleg"/>
|
||||
<property name="password" value="password"/>
|
||||
<property name="clientMode" value="1"/>
|
||||
<property name="fileType" value="2"/>
|
||||
<property name="useClientMode" value="true"/>
|
||||
<property name="cipherSuites" value="a,b.c"/>
|
||||
<property name="keyManager" ref="keyManager"/>
|
||||
<property name="protocol" value="SSL"/>
|
||||
<property name="trustManager" ref="trustManager"/>
|
||||
<property name="prot" value="P"/>
|
||||
<property name="needClientAuth" value="true"/>
|
||||
<property name="authValue" value="oleg"/>
|
||||
<property name="sessionCreation" value="true"/>
|
||||
<property name="protocols" value="SSL, TLS"/>
|
||||
<property name="implicit" value="true"/>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Every time an adapter requests a session object from its <interfacename>SessionFactory</interfacename> the session is
|
||||
returned from a session pool maintained by a caching wrapper around the factory. A Session in the session pool might go stale
|
||||
(if it has been disconnected by the server due to inactivity) so the <interfacename>SessionFactory</interfacename>
|
||||
will perform validation to make sure that it never returns a stale session to the adapter. If a stale session was encountered,
|
||||
it will be removed from the pool, and a new one will be created.
|
||||
<note>
|
||||
If you experience connectivity problems and would like to trace Session creation as well as see which Sessions are
|
||||
polled you may enable it by setting the logger to TRACE level (e.g., log4j.category.org.springframework.integration.file=TRACE)
|
||||
</note>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Now all you need to do is inject these session factories into your adapters. Obviously the protocol (FTP or FTPS) that an adapter will
|
||||
use depends on the type of session factory that has been injected into the adapter.
|
||||
</para>
|
||||
<para>
|
||||
<note>
|
||||
A more practical way to provide values for <emphasis>FTP/FTPS Session Factories</emphasis> is by using Spring's property
|
||||
placeholder support (See: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-placeholderconfigurer).
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="ftp-inbound">
|
||||
<title>FTP Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The <emphasis>FTP Inbound Channel Adapter</emphasis> is a special listener that will connect to the FTP server and will listen
|
||||
for the remote directory events (e.g., new file created) at which point it will initiate a file transfer.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-ftp:inbound-channel-adapter id="ftpInbound"
|
||||
channel="ftpChannel"
|
||||
session-factory="ftpSessionFactory"
|
||||
charset="UTF-8"
|
||||
auto-create-local-directory="true"
|
||||
delete-remote-files="true"
|
||||
filename-pattern="*.txt"
|
||||
remote-directory="some/remote/path"
|
||||
remote-file-separator="/"
|
||||
local-filename-generator-expression="#this.toUpperCase() + '.a'"
|
||||
local-directory=".">
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int-ftp:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
As you can see from the configuration above you can configure an <emphasis>FTP Inbound Channel Adapter</emphasis> via the <code>inbound-channel-adapter</code>
|
||||
element while also providing values for various attributes such as <code>local-directory</code>, <code>filename-pattern</code>
|
||||
(which is based on simple pattern matching, not regular expressions), and of course the reference to a <code>session-factory</code>.
|
||||
</para>
|
||||
<para>
|
||||
By default the transferred file will carry the same name as the original file. If you want to override this behavior you
|
||||
can set the <code>local-filename-generator-expression</code> attribute which allows you to provide a SpEL Expression to generate
|
||||
the name of the local file. Unlike outbound gateways and adapters where the root object of the SpEL Evaluation Context
|
||||
is a <classname>Message</classname>, this inbound adapter does not yet have the Message at the time of evaluation since
|
||||
that's what it ultimately generates with the transferred file as its payload. So, the root object of the SpEL Evaluation Context
|
||||
is the original name of the remote file (String).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Some times file filtering based on the simple pattern specified via <code>filename-pattern</code> attribute might not be
|
||||
sufficient. If this is the case, you can use the <code>filename-regex</code> attribute to specify a Regular Expression
|
||||
(e.g. <code>filename-regex=".*\.test$"</code>). And of course if you need complete control you can use <code>filter</code>
|
||||
attribute and provide a reference to any custom implementation of the
|
||||
<classname>org.springframework.integration.file.filters.FileListFilter</classname>, a strategy interface for filtering a
|
||||
list of files.
|
||||
</para>
|
||||
<note>
|
||||
As of Spring Integration 2.0.2, we have added a 'remote-file-separator' attribute. That allows you to configure a
|
||||
file separator character to use if the default '/' is not applicable for your particular environment.
|
||||
</note>
|
||||
<para>
|
||||
Please refer to the schema for more details on these attributes.
|
||||
</para>
|
||||
<para>
|
||||
It is also important to understand that the <emphasis>FTP Inbound Channel Adapter</emphasis> is a <emphasis>Polling Consumer</emphasis> and
|
||||
therefore you must configure a poller (either via a global default or a local sub-element).
|
||||
Once a file has been transferred, a Message with a <classname>java.io.File</classname> as its payload will be generated and sent to the channel
|
||||
identified by the <code>channel</code> attribute.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>More on File Filtering and Large Files</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
Some times the file that just appeared in the monitored (remote) directory is not complete. Typically such a file
|
||||
will be written with temporary extension (e.g., foo.txt.writing) and then renamed after the writing process finished.
|
||||
As a user in most cases you are only interested in files that are complete and would like to filter only files that are complete.
|
||||
To handle these scenarios you can use the filtering support provided by the <code>filename-pattern</code>, <code>filename-regex</code>
|
||||
and <code>filter</code> attributes. Here is an example that uses a custom Filter implementation.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-ftp:inbound-channel-adapter
|
||||
channel="ftpChannel"
|
||||
session-factory="ftpSessionFactory"
|
||||
filter="customFilter"
|
||||
local-directory="file:/my_transfers">
|
||||
remote-directory="some/remote/path"
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int-ftp:inbound-channel-adapter>
|
||||
|
||||
<bean id="customFilter" class="org.example.CustomFilter"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Poller configuration notes for the inbound FTP adapter</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
The job of the inbound FTP adapter consists of two tasks:
|
||||
<emphasis>1) Communicate with a remote server in order to transfer files from a remote directory to a local directory.</emphasis>
|
||||
<emphasis>2) For each transferred file, generate a Message with that file as a payload and send it to the channel identified by the 'channel' attribute.</emphasis>
|
||||
|
||||
That is why they are called 'channel-adapters' rather than just 'adapters'. The main job of such an adapter is to generate a
|
||||
Message to be sent to a Message Channel. Essentially, the second task mentioned above takes precedence in such a way that
|
||||
*IF* your local directory already has one or more files it will first generate Messages from those, and *ONLY*
|
||||
when all local files have been processed, will it initiate the remote communication to retrieve more files.
|
||||
</para>
|
||||
<para>
|
||||
Also, when configuring a trigger on the poller you should pay close attention to the <code>max-messages-per-poll</code>
|
||||
attribute. Its default value is 1 for all <classname>SourcePollingChannelAdapter</classname> instances (including FTP).
|
||||
This means that as soon as one file is processed, it will wait for the next execution time as determined by your
|
||||
trigger configuration. If you happened to have one or more files sitting in the <code>local-directory</code>, it would process
|
||||
those files before it would initiate communication with the remote FTP server. And, if the <code>max-messages-per-poll</code>
|
||||
were set to 1 (default), then it would be processing only one file at a time with intervals as defined by your trigger,
|
||||
essentially working as <emphasis>one-poll = one-file</emphasis>.
|
||||
</para>
|
||||
<para>
|
||||
For typical file-transfer use cases, you most likely want the opposite behavior: to process all the files you can for each
|
||||
poll and only then wait for the next poll. If that is the case, set <code>max-messages-per-poll</code> to -1. Then, on
|
||||
each poll, the adapter will attempt to generate as many Messages as it possibly can. In other words, it will process
|
||||
everything in the local directory, and then it will connect to the remote directory to transfer everything that is available
|
||||
there to be processed locally. Only then is the poll operation considered complete, and the poller will wait for the next execution time.
|
||||
</para>
|
||||
<para>
|
||||
You can alternatively set the 'max-messages-per-poll' value to a positive value indicating the upward limit of Messages to be created
|
||||
from files with each poll. For example, a value of 10 means that on each poll it will attempt to process no more than 10 files.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="ftp-outbound">
|
||||
<title>FTP Outbound Channel Adapter</title>
|
||||
|
||||
<para>
|
||||
The <emphasis>FTP Outbound Channel Adapter</emphasis> relies upon a <classname>MessageHandler</classname> implementation that will connect to the
|
||||
FTP server and initiate an FTP transfer for every file it receives in the payload of incoming Messages. It also supports several
|
||||
representations of the <emphasis>File</emphasis> so you are not limited only to java.io.File typed payloads.
|
||||
The <emphasis>FTP Outbound Channel Adapter</emphasis>
|
||||
supports the following payloads: 1) <classname>java.io.File</classname> - the actual file object;
|
||||
2) <classname>byte[]</classname> - a byte array that represents the file contents; and 3) <classname>java.lang.String</classname> -
|
||||
text that represents the file contents.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-ftp:outbound-channel-adapter id="ftpOutbound"
|
||||
channel="ftpChannel"
|
||||
session-factory="ftpSessionFactory"
|
||||
charset="UTF-8"
|
||||
remote-file-separator="/"
|
||||
filename-generator="fileNameGenerator"/>]]></programlisting>
|
||||
|
||||
As you can see from the configuration above you can configure an <emphasis>FTP Outbound Channel Adapter</emphasis> via the
|
||||
<code>outbound-channel-adapter</code> element while also providing values for various attributes such as <code>filename-generator</code>
|
||||
(an implementation of the <classname>org.springframework.integration.file.FileNameGenerator</classname> strategy interface),
|
||||
a reference to a <code>client-factory</code>, as well as other attributes. Please refer to the schema for more details on
|
||||
the available attributes.
|
||||
<note>
|
||||
By default Spring Integration will use <classname>org.springframework.integration.file.DefaultFileNameGenerator</classname> if none is specified.
|
||||
<classname>DefaultFileNameGenerator</classname> will determine the file name based on the value of the <code>file_name</code> header (if it exists)
|
||||
in the MessageHeaders, or if the payload of the Message is already a <classname>java.io.File</classname>, then it will use the original name of that file.
|
||||
</note>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<important>
|
||||
Defining certain values (e.g., remote-directory) might be platform/ftp server dependent. For example as it
|
||||
was reported on this forum http://forum.springsource.org/showthread.php?p=333478&posted=1#post333478 on some
|
||||
platforms you must add slash to the end of the directory definition (e.g., remote-directory="/foo/bar/"
|
||||
instead of remote-directory="/foo/bar")
|
||||
</important>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
<section id="ftp-outbound-gateway">
|
||||
<title>FTP Outbound Gateway</title>
|
||||
|
||||
<para>
|
||||
The <emphasis>FTP Outbound Gateway</emphasis> provides a limited set of commands to interact with a remote FTP/FTPS server.
|
||||
<para>
|
||||
Commands supported are:
|
||||
<itemizedlist>
|
||||
<listitem>ls (list files)</listitem>
|
||||
<listitem>get (retrieve file(s))</listitem>
|
||||
<listitem>rm (remove file(s))</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
ls supports the following options:
|
||||
<itemizedlist>
|
||||
<listitem>-1 - just retrieve a list of filenames, default is to retrieve a
|
||||
list of <classname>FileInfo</classname> objects.</listitem>
|
||||
<listitem>-a - include all files (including those starting with '.')</listitem>
|
||||
<listitem>-f - do not sort the list</listitem>
|
||||
<listitem>-dirs - include directories (excluded by default)</listitem>
|
||||
<listitem>-links - include symbolic links (excluded by default)</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
In addition, filename filtering is provided, in the same manner as the
|
||||
<classname>inbound-channel-adapter</classname>.
|
||||
</para>
|
||||
<para>
|
||||
The message payload resulting from an <emphasis>ls</emphasis> operation is a list of file names,
|
||||
or a list of <classname>FileInfo</classname> objects. These objects provide
|
||||
information such as modified time, permissions etc.
|
||||
</para>
|
||||
<para>
|
||||
The remote directory that the <emphasis>ls</emphasis> command acted on is provided
|
||||
in the <classname>file_remoteDirectory</classname> header.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>get</emphasis> supports the following option:
|
||||
<itemizedlist>
|
||||
<listitem>-P - preserve the timestamp of the remote file</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
The message payload resulting from a <emphasis>get</emphasis> operation is a
|
||||
<classname>File</classname> object representing the retrieved file.
|
||||
</para>
|
||||
<para>
|
||||
The remote directory is provided in the <classname>file_remoteDirectory</classname> header, and the filename is
|
||||
provided in the <classname>file_remoteFile</classname> header.
|
||||
</para>
|
||||
<para></para>
|
||||
<para>
|
||||
The <emphasis>rm</emphasis> command has no options.
|
||||
</para>
|
||||
<para>
|
||||
<note>
|
||||
Filters are not supported with the <emphasis>rm</emphasis> command.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
The message payload resulting from an <emphasis>rm</emphasis> operation is Boolean.TRUE if the
|
||||
remove was successful, Boolean.FALSE otherwise.
|
||||
The remote directory is provided in the <classname>file_remoteDirectory</classname> header, and the filename is
|
||||
provided in the <classname>file_remoteFile</classname> header.
|
||||
</para>
|
||||
<para></para>
|
||||
<para>
|
||||
In each case, the PATH that these commands act on is provided by the 'expression'
|
||||
property of the gateway.
|
||||
</para>
|
||||
</para>
|
||||
<para>
|
||||
Here is an example of a gateway configured for an ls command...
|
||||
<programlisting language="xml"><![CDATA[<int-ftp:outbound-gateway id="gateway1"
|
||||
session-factory="ftpSessionFactory"
|
||||
request-channel="inbound1"
|
||||
command="ls"
|
||||
command-options="-1"
|
||||
expression="payload"
|
||||
reply-channel="toSplitter"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The payload of the message sent to the toSplitter channel is a list of String objects
|
||||
containing the filename of each file. If the <classname>command-options</classname> was
|
||||
omitted, it would be a list of <classname>FileInfo</classname> objects. Options are
|
||||
provided space-delimited, e.g. <classname>command-options="-1 -dirs -links"</classname>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="ftp-session-caching">
|
||||
<title>FTP Session Caching</title>
|
||||
<para>
|
||||
As of version 2.1 we've exposed more flexibility with regard to session management for remote file adapters (e.g., FTP, SFTP etc).
|
||||
In previous versions the sessions were cached automatically by default. We did expose a <code>cache-sessions</code> attribute for
|
||||
disabling the auto caching, but that solution did not provide a way to configure other session caching attributes. For example, one
|
||||
of the requested features was to support a limit on the number of sessions created since a remote server may impose a limit on the
|
||||
number of client connections. To support that requirement and other configuration options, we decided to promote explicit definition
|
||||
of the <classname>CachingSessionFactory</classname> instance. That provides the <code>sessionCacheSize</code> and <code>sessionWaitTimeout</code>
|
||||
properties. As its name suggests, the <code>sessionCacheSize</code> property controls how many active sessions this adapter will
|
||||
maintain in its cache (the DEFAULT is unbounded). If the <code>sessionCacheSize</code> threshold has been reached, any attempt to
|
||||
acquire another session will block until either one of the cached sessions becomes available or until the wait time for a Session
|
||||
expires (the DEFAULT wait time is Integer.MAX_VALUE). The <code>sessionWaitTimeout</code> property enables configuration of that value.
|
||||
</para>
|
||||
<para>
|
||||
If you want your Sessions to be cached, simply configure your default Session Factory as described above and then
|
||||
wrap it in an instance of <classname>CachingSessionFactory</classname> where you may provide those additional properties.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<bean id="ftpSessionFactory" class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
|
||||
<property name="host" value="localhost"/>
|
||||
</bean>
|
||||
|
||||
<bean id="cachingSessionFactory" class="org.springframework.integration.file.remote.session.CachingSessionFactory">
|
||||
<constructor-arg ref="ftpSessionFactory"/>
|
||||
<constructor-arg value="10"/>
|
||||
<property name="sessionWaitTimeout" value="1000"/>
|
||||
</bean>]]></programlisting>
|
||||
|
||||
In the above example you see a <classname>CachingSessionFactory</classname> created with the
|
||||
<code>sessionCacheSize</code> set to 10 and the <code>sessionWaitTimeout</code> set to 1 second (its value is in millliseconds).
|
||||
|
||||
</para>
|
||||
</section>
|
||||
</chapter>
|
||||
409
src/reference/docbook/gateway.xml
Normal file
@@ -0,0 +1,409 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="gateway"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Messaging Gateways</title>
|
||||
<para>
|
||||
The primary purpose of a Gateway is to hide the messaging API provided by
|
||||
Spring Integration. It allows your application's business logic to be completely
|
||||
unaware of the Spring Integration API and using a generic Gateway, your code
|
||||
interacts instead with a simple interface, only.
|
||||
</para>
|
||||
<section id="gateway-proxy">
|
||||
<title>Enter the GatewayProxyFactoryBean</title>
|
||||
<para>
|
||||
As mentioned above, it would be great to have no dependency on the Spring
|
||||
Integration API at all - including the gateway class. For that reason, Spring
|
||||
Integration provides the <classname>GatewayProxyFactoryBean</classname> that
|
||||
generates a proxy for any interface and internally invokes the gateway
|
||||
methods shown below. Using dependency injection you can then expose the interface
|
||||
to your business methods.
|
||||
</para>
|
||||
<para>
|
||||
Here is an example of an interface that can be used to interact with Spring
|
||||
Integration:
|
||||
</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[package org.cafeteria;
|
||||
|
||||
public interface Cafe {
|
||||
|
||||
void placeOrder(Order order);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
</section>
|
||||
<section id="gateway-namespace">
|
||||
<title>Gateway XML Namespace Support</title>
|
||||
<para>
|
||||
Namespace support is also
|
||||
provided which allows you to configure such an interface as a service as demonstrated by the following example.
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:gateway id="cafeService"
|
||||
service-interface="org.cafeteria.Cafe"
|
||||
default-request-channel="requestChannel"
|
||||
default-reply-channel="replyChannel"/>]]></programlisting>
|
||||
<para>
|
||||
With this configuration defined, the "cafeService" can now be injected into other beans, and the code that invokes the methods on that
|
||||
proxied instance of the Cafe interface has no awareness of the Spring Integration API. The general
|
||||
approach is similar to that of Spring Remoting (RMI, HttpInvoker, etc.). See the "Samples" Appendix for
|
||||
an example that uses this "gateway" element (in the Cafe demo).
|
||||
</para>
|
||||
</section>
|
||||
<section id="gateway-default-reply-channel">
|
||||
<title>Setting the Default Reply Channel</title>
|
||||
<para>
|
||||
Typically you don't have to specify the <code>default-reply-channel</code>,
|
||||
since a Gateway will auto-create a temporary, anonymous reply channel,
|
||||
where it will listen for the reply. However, there are some cases which
|
||||
may prompt you to define a <code>default-reply-channel</code> (or <code>reply-channel</code>
|
||||
with adapter gateways such as HTTP, JMS, etc.).
|
||||
</para>
|
||||
<para>
|
||||
For some background, we'll quickly discuss some of the inner-workings of the Gateway.
|
||||
A Gateway will create a temporary point-to-point reply channel which is anonymous and is added
|
||||
to the Message Headers with the name <code>replyChannel</code>.
|
||||
When providing an explicit <code>default-reply-channel</code> (<code>reply-channel</code> with remote adapter gateways),
|
||||
you have the option to point to a publish-subscribe channel, which is so named because you can add more than one subscriber to it.
|
||||
Internally Spring Integration will create a Bridge between the temporary <code>replyChannel</code> and the explicitly defined
|
||||
<code>default-reply-channel</code>.
|
||||
</para>
|
||||
<para>
|
||||
So let's say you want your reply to go not only to the gateway, but also to some other consumer. In this case you
|
||||
would want two things: <emphasis>a) a named channel you can subscribe to and b) that channel is a publish-subscribe-channel.</emphasis>
|
||||
The default strategy used by the gateway will not satisfy those needs, because the reply channel added to the header is anonymous and
|
||||
point-to-point. This means that no other subscriber can get a handle to it and even if it could, the channel
|
||||
has point-to-point behavior such that only one subscriber would get the Message. So by defining a <code>default-reply-channel</code>
|
||||
you can point to a channel of your choosing, which in this case would be a <code>publish-subscribe-channel</code>.
|
||||
The Gateway would create a bridge from it to the temporary, anonymous reply channel that is stored in the header.
|
||||
</para>
|
||||
<para>
|
||||
Another case where you might want to provide a reply channel explicitly is for monitoring or auditing via an interceptor
|
||||
(e.g., wiretap). You need a named channel in order to configure a Channel Interceptor.
|
||||
</para>
|
||||
</section>
|
||||
<section id="gateway-configuration-annotations">
|
||||
<title>Gateway Configuration with Annotations and/or XML</title>
|
||||
<para>
|
||||
The reason that the attributes on the 'gateway' element are named 'default-request-channel' and
|
||||
'default-reply-channel' is that you may also provide per-method channel references by using the
|
||||
<classname>@Gateway</classname> annotation.
|
||||
</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[ public interface Cafe {
|
||||
|
||||
@Gateway(requestChannel="orders")
|
||||
void placeOrder(Order order);
|
||||
|
||||
}]]></programlisting>
|
||||
<para>
|
||||
You may alternatively provide such content in <code>method</code> sub-elements if you prefer XML configuration (see the next paragraph).
|
||||
</para>
|
||||
<para>
|
||||
It is also possible to pass values to be interpreted as Message headers on the Message
|
||||
that is created and sent to the request channel by using the @Header annotation:
|
||||
</para>
|
||||
<programlisting language="java"><![CDATA[ public interface FileWriter {
|
||||
|
||||
@Gateway(requestChannel="filesOut")
|
||||
void write(byte[] content, @Header(FileHeaders.FILENAME) String filename);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
<para>
|
||||
If you prefer the XML approach of configuring Gateway methods, you can provide <emphasis>method</emphasis> sub-elements
|
||||
to the gateway configuration.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:gateway id="myGateway" service-interface="org.foo.bar.TestGateway"
|
||||
default-request-channel="inputC">
|
||||
<int:method name="echo" request-channel="inputA" reply-timeout="2" request-timeout="200"/>
|
||||
<int:method name="echoUpperCase" request-channel="inputB"/>
|
||||
<int:method name="echoViaDefault"/>
|
||||
</int:gateway>]]></programlisting>
|
||||
|
||||
<para>
|
||||
You can also provide individual headers per method invocation via XML.
|
||||
This could be very useful if the headers you want to set are static in nature and you don't want
|
||||
to embed them in the gateway's method signature via <classname>@Header</classname> annotations.
|
||||
For example, in the Loan Broker example we want to influence how aggregation of the Loan quotes
|
||||
will be done based on what type of request was initiated (single quote or all quotes). Determining the
|
||||
type of the request by evaluating what gateway method was invoked, although possible, would
|
||||
violate the separation of concerns paradigm (the method is a java artifact), but expressing your
|
||||
intention (meta information) via Message headers is natural in a Messaging architecture.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:gateway id="loanBrokerGateway"
|
||||
service-interface="org.springframework.integration.loanbroker.LoanBrokerGateway">
|
||||
<int:method name="getLoanQuote" request-channel="loanBrokerPreProcessingChannel">
|
||||
<int:header name="RESPONSE_TYPE" value="BEST"/>
|
||||
</int:method>
|
||||
<int:method name="getAllLoanQuotes" request-channel="loanBrokerPreProcessingChannel">
|
||||
<int:header name="RESPONSE_TYPE" value="ALL"/>
|
||||
</int:method>
|
||||
</int:gateway>]]></programlisting>
|
||||
<para>
|
||||
In the above case you can clearly see how a different value will be set for the 'RESPONSE_TYPE'
|
||||
header based on the gateway's method.
|
||||
</para>
|
||||
|
||||
</section>
|
||||
<section id="gateway-calling-no-argument-methods">
|
||||
<title>Invoking No-Argument Methods</title>
|
||||
<para>
|
||||
When invoking methods on a Gateway interface that do not have any arguments,
|
||||
the default behavior is to <emphasis>receive</emphasis> a <code>Message</code> from a
|
||||
<interfacename>PollableChannel</interfacename>.
|
||||
</para>
|
||||
<para>
|
||||
At times however, you may want to trigger no-argument methods so that
|
||||
you can in fact interact with other components downstream that do not require
|
||||
user-provided parameters, e.g. triggering no-argument SQL calls or Stored
|
||||
Procedures.
|
||||
</para>
|
||||
<para>
|
||||
In order to achieve <emphasis>send-and-receive</emphasis> semantics, you must provide a payload.
|
||||
In order to generate a payload, method parameters on the interface are
|
||||
not necessary. You can either use the <code>@Payload</code> annotation
|
||||
or the <code>payload-expression</code> attribute in XML on the <code>method</code>
|
||||
sub-element. Below please find a few examples of what the payloads could be:
|
||||
</para>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>a literal string</listitem>
|
||||
<listitem>#method (for the method name)</listitem>
|
||||
<listitem>new java.util.Date()</listitem>
|
||||
<listitem>@someBean.someMethod()'s return value</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<para>
|
||||
Here is an example using the <code>@Payload</code> annotation:
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[public interface Cafe {
|
||||
|
||||
@Payload("new java.util.Date()")
|
||||
List<Order> retrieveOpenOrders();
|
||||
|
||||
}]]></programlisting>
|
||||
<para>
|
||||
If a method has no argument and no return value, but does contain a
|
||||
payload expression, it will be treated as a <emphasis>send-only</emphasis>
|
||||
operation.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="gateway-error-handling">
|
||||
<title>Error Handling </title>
|
||||
<para>
|
||||
|
||||
Of course, the Gateway invocation might result in errors.
|
||||
By default any error that has occurred downstream will be re-thrown as a
|
||||
<classname>MessagingException</classname> (RuntimeException)
|
||||
upon the Gateway's method invocation. However there are times when you may want
|
||||
to simply log the error rather than propagating it, or you may want to treat an
|
||||
Exception as a valid reply, by mapping it to a Message that will conform to some
|
||||
"error message" contract that the caller understands. To accomplish this, our
|
||||
Gateway provides support for a Message Channel dedicated to the errors via the
|
||||
<emphasis>error-channel</emphasis> attribute. In the example below, you can see
|
||||
that a 'transformer' is used to create a reply Message from the Exception.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:gateway id="sampleGateway"
|
||||
default-request-channel="gatewayChannel"
|
||||
service-interface="foo.bar.SimpleGateway"
|
||||
error-channel="exceptionTransformationChannel"/>
|
||||
|
||||
<int:transformer input-channel="exceptionTransformationChannel"
|
||||
ref="exceptionTransformer" method="createErrorResponse"/>
|
||||
]]></programlisting>
|
||||
<para>
|
||||
The <emphasis>exceptionTransformer</emphasis> could be a simple POJO that
|
||||
knows how to create the expected error response objects. That would then be
|
||||
the payload that is sent back to the caller. Obviously, you could do many
|
||||
more elaborate things in such an "error flow" if necessary. It might involve
|
||||
routers (including Spring Integration's ErrorMessageExceptionTypeRouter),
|
||||
filters, and so on. Most of the time, a simple 'transformer' should be sufficient,
|
||||
however.
|
||||
</para>
|
||||
<para>
|
||||
Alternatively, you might want to only log the Exception (or send it somewhere
|
||||
asynchronously). If you provide a one-way flow, then nothing would be sent
|
||||
back to the caller. In the case that you want to completely suppress Exceptions,
|
||||
you can provide a reference to the global "nullChannel" (essentially a /dev/null
|
||||
approach). Finally, as mentioned above, if no "error-channel" is defined at all,
|
||||
then the Exceptions will propagate as usual.
|
||||
</para>
|
||||
<para>
|
||||
<important>
|
||||
Exposing the messaging system via simple POJI Gateways obviously provides benefits, but "hiding" the reality
|
||||
of the underlying messaging system does come at a price so there are certain things you should consider.
|
||||
|
||||
We want our Java method to return as quickly as possible and not hang for an indefinite amount of time while
|
||||
the caller is waiting on it to return (void, return value, or a thrown Exception). When regular methods are
|
||||
used as a proxies in front of the Messaging system, we have to take into account the potentially asynchronous
|
||||
nature of the underlying messaging. This means that there might
|
||||
be a chance that a Message that was initiated by a Gateway could be dropped by a Filter, thus never reaching a
|
||||
component that is responsible for producing a reply. Some Service Activator method might result in an Exception,
|
||||
thus providing no reply (as we don't generate Null messages). So as you can see there are multiple scenarios
|
||||
where a reply message might not be coming. That is perfectly natural in messaging systems. However think about the
|
||||
implication on the gateway method. The Gateway's method input arguments were incorporated into a Message and
|
||||
sent downstream. The reply Message would be converted to a return value of the Gateway's method. So you might want
|
||||
to ensure that for each Gateway call there will always be a reply Message.
|
||||
Otherwise, your Gateway method might never return and will hang indefinitely.
|
||||
One of the ways of handling this situation is via an Asynchronous Gateway (explained later in this section). Another way of handling it is to explicitly set the reply-timeout attribute. That way, the gateway will not hang any longer than the time specified by the reply-timeout and will return 'null' if that timeout does elapse. Finally, you might want to consider setting downstream flags such as 'requires-reply' on
|
||||
a service-activator or 'throw-exceptions-on-rejection' on a filter. These options will be discussed in more detail in the final section
|
||||
of this chapter.
|
||||
</important>
|
||||
</para>
|
||||
</section>
|
||||
<section id="async-gateway">
|
||||
<title>Asynchronous Gateway</title>
|
||||
<para>
|
||||
As a pattern the Messaging Gateway is a very nice way to hide messaging-specific code while still exposing the full capabilities of the
|
||||
messaging system. As you've seen, the <classname>GatewayProxyFactoryBean</classname> provides a convenient way to expose a Proxy over a service-interface
|
||||
thus giving you POJO-based access to a messaging system (based on objects in your own domain, or primitives/Strings, etc). But when a
|
||||
gateway is exposed via simple POJO methods which return values it does imply that for each Request message (generated when the method is invoked)
|
||||
there must be a Reply message (generated when the method has returned). Since Messaging systems naturally are asynchronous you may not always be
|
||||
able to guarantee the contract where <emphasis>"for each request there will always be be a reply"</emphasis>.
|
||||
With Spring Integration 2.0 we are introducing support for an <emphasis>Asynchronous Gateway</emphasis> which is a convenient way to initiate
|
||||
flows where you may not know if a reply is expected or how long will it take for replies to arrive.
|
||||
</para>
|
||||
<para>
|
||||
A natural way to handle these types of scenarios in Java would be relying upon <emphasis>java.util.concurrent.Future</emphasis> instances, and
|
||||
that is exactly what Spring Integration uses to support an <emphasis>Asynchronous Gateway</emphasis>.
|
||||
</para>
|
||||
<para>
|
||||
From the XML configuration, there is nothing different and you still define <emphasis>Asynchronous Gateway</emphasis> the same way as a regular Gateway.
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:gateway id="mathService"
|
||||
service-interface="org.springframework.integration.sample.gateway.futures.MathServiceGateway"
|
||||
default-request-channel="requestChannel"/>]]></programlisting>
|
||||
<para>
|
||||
However the Gateway Interface (service-interface) is a bit different.
|
||||
</para>
|
||||
<programlisting language="java">public interface MathServiceGateway {
|
||||
Future<Integer> multiplyByTwo(int i);
|
||||
}</programlisting>
|
||||
|
||||
<para>
|
||||
As you can see from the example above the return type for the gateway method is a <classname>Future</classname>. When
|
||||
<classname>GatewayProxyFactoryBean</classname> sees that the
|
||||
return type of the gateway method is a <classname>Future</classname>, it immediately switches to the async mode by utilizing
|
||||
an <classname>AsyncTaskExecutor</classname>. That is all. The call to such a method always returns immediately with a <classname>Future</classname> instance.
|
||||
Then, you can interact with the <classname>Future</classname> at your own pace to get the result, cancel, etc. And, as with
|
||||
any other use of Future instances, calling get() may reveal a timeout, an execution exception, and so on.
|
||||
<programlisting language="java">MathServiceGateway mathService = ac.getBean("mathService", MathServiceGateway.class);
|
||||
Future<Integer> result = mathService.multiplyByTwo(number);
|
||||
// do something else here since the reply might take a moment
|
||||
int finalResult = result.get(1000, TimeUnit.SECONDS);</programlisting>
|
||||
For a more detailed example, please refer to the <emphasis>async-gateway</emphasis> sample distributed within the Spring Integration samples.
|
||||
</para>
|
||||
|
||||
<para><emphasis>Asynchronous Gateway and AsyncTaskExecutor</emphasis></para>
|
||||
<para>
|
||||
By default <classname>GatewayProxyFactoryBean</classname> uses <classname>org.springframework.core.task.SimpleAsyncTaskExecutor</classname>
|
||||
when submitting internal <classname>AsyncInvocationTask</classname> instances for any gateway method whose
|
||||
return type is <classname>Future.class</classname>. However the <literal>async-executor</literal> attribute in the
|
||||
<literal><gateway/></literal> element's configuration allows you to provide a reference to any implementation of
|
||||
<classname>java.util.concurrent.Executor</classname> available within the Spring application context.
|
||||
</para>
|
||||
</section>
|
||||
<section>
|
||||
<title>Gateway behavior when no response arrives</title>
|
||||
<para>
|
||||
As it was explained earlier, the Gateway provides a convenient way of interacting with a Messaging system via POJO method
|
||||
invocations, but realizing that a typical method invocation, which is generally expected to always return (even with an Exception),
|
||||
might not always map one-to-one to message exchanges (e.g., a reply message might not arrive - which is equivalent to a
|
||||
method not returning). It is important to go over several scenarios especially in the Sync Gateway case and understand
|
||||
the default behavior of the Gateway and how to deal with these scenarios to make the Sync Gateway behavior more
|
||||
predictable regardless of the outcome of the message flow that was initialed from such Gateway.
|
||||
</para>
|
||||
<para>
|
||||
There are certain attributes that could be configured to make Sync Gateway behavior more predictable,
|
||||
but some of them might not always work as you might have expected. One of them is <emphasis>reply-timeout</emphasis>.
|
||||
So, lets look at the <emphasis>reply-timeout</emphasis> attribute and see how it can/can't influence the behavior
|
||||
of the Sync Gateway in various scenarios. We will look at single-threaded scenario
|
||||
(all components downstream are connected via Direct Channel) and multi-threaded scenarios
|
||||
(e.g., somewhere downstream you may have Pollable or Executor Channel which breaks single-thread boundary)
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Long running process downstream</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Sync Gateway - single-threaded</emphasis>.
|
||||
If a component downstream is still running (e.g., infinite loop or a very slow service), then setting a <emphasis>reply-timeout</emphasis>
|
||||
has no effect and the Gateway method call will not return until such downstream service exits (via return or exception).
|
||||
<emphasis>Sync Gateway - multi-threaded</emphasis>.
|
||||
If a component downstream is still running (e.g., infinite loop or a very slow service), in a multi-threaded message
|
||||
flow setting the <emphasis>reply-timeout</emphasis> will have an effect by allowing gateway method invocation to
|
||||
return once the timeout has been reached, since the <classname>GatewayProxyFactoryBean</classname> will simply
|
||||
poll on the reply channel waiting for a message until the timeout expires. However it could result in a 'null' return
|
||||
from the Gateway method if the timeout has been reached before the actual reply was produced. It is also important to understand that
|
||||
the reply message (if produced) will be sent to a reply channel after the Gateway method invocation might have returned, so you must be aware of that and design your flow with this in mind.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Downstream component returns 'null'</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Sync Gateway - single-threaded</emphasis>.
|
||||
If a component downstream returns 'null' and no <emphasis>reply-timeout</emphasis> has been configured, the Gateway
|
||||
method call will hang indefinitely unless: a) a <emphasis>reply-timeout</emphasis> has been configured or b) the
|
||||
<emphasis>requires-reply</emphasis> attribute has been set on the downstream component (e.g., service-activator)
|
||||
that might return 'null'. In this case, an Exception would be thrown and propagated to the Gateway.
|
||||
<emphasis>Sync Gateway - multi-threaded</emphasis>. Behavior is the same as above.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Downstream component return signature is 'void' while Gateway method signature is non-void</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Sync Gateway - single-threaded</emphasis>.
|
||||
If a component downstream returns 'void' and no <emphasis>reply-timeout</emphasis> has been configured,
|
||||
the Gateway method call will hang indefinitely unless a <emphasis>reply-timeout</emphasis> has been configured
|
||||
<emphasis>Sync Gateway - multi-threaded</emphasis> Behavior is the same as above.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Downstream component results in Runtime Exception (regardless of the method signature)</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Sync Gateway - single-threaded</emphasis>.
|
||||
If a component downstream throws a Runtime Exception, such exception will be propagated via an Error Message back to
|
||||
the gateway and re-thrown.
|
||||
<emphasis>Sync Gateway - multi-threaded</emphasis> Behavior is the same as above.
|
||||
</para>
|
||||
<para>
|
||||
<important>
|
||||
It is also important to understand that by default <emphasis>reply-timeout</emphasis> is unbounded* which means that
|
||||
if not explicitly set there are several scenarios (described above) where your Gateway method invocation might
|
||||
hang indefinitely. So, make sure you analyze your flow and if there is even a remote possibility of one of these
|
||||
scenarios to occur, set the <emphasis>reply-timeout</emphasis> attribute to a 'safe' value or, even better,
|
||||
set the <emphasis>requires-reply</emphasis> attribute of the downstream component to 'true' to ensure a timely response
|
||||
as produced by the throwing of an Exception as soon as that downstream component does return null internally.
|
||||
But also, realize that there are some scenarios (see the very first one)
|
||||
where <emphasis>reply-timeout</emphasis> will not help. That means it is also important to analyze your message
|
||||
flow and decide when to use a Sync Gateway vs an Async Gateway. As you've seen the latter case is simply a matter of
|
||||
defining Gateway methods that return Future instances. Then, you are guaranteed to receive that return value, and
|
||||
you will have more granular control over the results of the invocation.
|
||||
<para>
|
||||
Also, when dealing with a Router you should remember that setting the <emphasis>resolution-required</emphasis> attribute to 'true'
|
||||
will result in an Exception thrown by the router if it can not resolve a particular channel. Likewise, when dealing with a Filter,
|
||||
you can set the <emphasis>throw-exception-on-rejection</emphasis> attribute. In both of these cases, the resulting flow will
|
||||
behave like that containing a service-activator with the 'requires-reply' attribute. In other words, it will help to ensure
|
||||
a timely response from the Gateway method invocation.
|
||||
</para>
|
||||
<para>
|
||||
<note>
|
||||
<para>
|
||||
* <emphasis>reply-timeout</emphasis> is unbounded for <emphasis><gateway/></emphasis>
|
||||
elements (created by the GatewayProxyFactoryBean). Inbound gateways for external integration
|
||||
(ws, http, etc.) share many characteristics and attributes with these gateways. However,
|
||||
for those inbound gateways, the default <emphasis>reply-timeout</emphasis> is 1000
|
||||
milliseconds (1 second). If a downstream async handoff is made to another thread, you may need to
|
||||
increase this attribute to allow enough time for the flow to complete before the
|
||||
gateway times out.
|
||||
</para>
|
||||
</note>
|
||||
</para>
|
||||
</important>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
168
src/reference/docbook/gemfire.xml
Normal file
@@ -0,0 +1,168 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="gemfire"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude">
|
||||
<title>GemFire Support</title>
|
||||
<para>
|
||||
Spring Integration provides support for VMWare vFabric GemFire
|
||||
</para>
|
||||
<section id="gemfire-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
VMWare vFabric GemFire (GemFire) is a distributed data management platform providing a key-value data grid along with advanced distributed system features such as event processing, continuous querying, and
|
||||
remote function execution. This guide assumes
|
||||
some familiarity with <ulink url="http://www.gemstone.com/docs/6.6.RC/product/docs/html/user_guide/UserGuide_GemFire.html#Getting%20Started%20with%20Gemfire">GemFire</ulink>
|
||||
and its <ulink url="http://www.gemstone.com/docs/6.6.RC/product/docs/japi/index.html">API</ulink>.
|
||||
</para>
|
||||
<para>
|
||||
Spring integration provides support for GemFire by providing inbound adapters for entry and continuous query events,
|
||||
an outbound adapter to write entries to the cache, and <classname>MessageStore</classname> and <classname>MessageGroupStore</classname> implementations.
|
||||
Spring integration leverages the
|
||||
<ulink url="http://www.springsource.org/spring-gemfire">Spring Gemfire</ulink> project, providing a thin wrapper over its components.
|
||||
</para>
|
||||
<para>
|
||||
To configure the 'int-gfe' namespace, include the following elements within the headers of your XML configuration file:
|
||||
|
||||
<programlisting language="xml"><![CDATA[xmlns:int-gfe="http://www.springframework.org/schema/integration/gemfire"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration/gemfire
|
||||
http://www.springframework.org/schema/integration/gemfire/spring-integration-gemfire.xsd"]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
<section>
|
||||
<title>Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The <emphasis>inbound-channel-adapter</emphasis> produces messages on a channel triggered by a GemFire <classname>EntryEvent</classname>. GemFire
|
||||
generates events whenever an entry is CREATED, UPDATED, DESTROYED, or INVALIDATED in the associated region. The inbound channel adapter allows you to filter on a subset of these
|
||||
events. For example, you may want to only produce messages in response to an entry being CREATED. In addition, the inbound channel adapter can evaluate a SpEL
|
||||
expression if, for example, you want your message payload to contain an event property such as the new entry value.
|
||||
|
||||
<programlisting language="xml">
|
||||
<![CDATA[<gfe:cache/>
|
||||
<gfe:replicated-region id="region"/>
|
||||
<int-gfe:inbound-channel-adapter id="inputChannel" region="region"
|
||||
cache-events="CREATED" expression="newValue"/>]]>
|
||||
</programlisting>
|
||||
|
||||
In the above configuration, we are creating a GemFire <classname>Cache</classname> and <classname>Region</classname> using Spring GemFire's 'gfe' namespace.
|
||||
The inbound-channel-adapter requires a reference to the GemFire region for which the adapter will be listening for events. Optional attributes include <code>cache-events</code>
|
||||
which can contain a comma separated list of event types for which a message will be produced on the input channel. By default CREATED and UPDATED are enabled.
|
||||
Note that this adapter conforms to Spring integration conventions.
|
||||
If no <code>channel</code> attribute is provided, the channel will be created from the <code>id</code> attribute. This adapter also supports an <code>error-channel</code>.
|
||||
If <code>expression</code> is not provided the message payload will be a GemFire <classname>EntryEvent</classname>
|
||||
</para>
|
||||
</section>
|
||||
<section>
|
||||
<title>Continuous Query Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The <emphasis>cq-inbound-channel-adapter</emphasis> produces messages a channel triggered by a GemFire continuous query or <classname>CqEvent</classname> event. Spring GemFire introduced
|
||||
continuous query support in release 1.1, including a <classname>ContinuousQueryListenerContainer</classname> which provides a nice abstraction over the GemFire native API. This adapter requires a
|
||||
reference to a ContinuousQueryListenerContainer, and creates a listener for a given <code>query</code> and executes the query. The continuous query acts as an event source that will fire whenever its
|
||||
result set changes state.
|
||||
<note>
|
||||
GemFire queries are written in OQL and are scoped to the entire cache (not just one region). Additionally, continuous queries require a remote (i.e., running in a separate process or remote host)
|
||||
cache server. Please consult the <ulink url="http://www.gemstone.com/docs/6.6.RC/product/docs/html/user_guide/UserGuide_GemFire.html#Continuous%20Querying">GemFire documentation</ulink> for more information on
|
||||
implementing continuous queries.
|
||||
</note>
|
||||
|
||||
|
||||
<programlisting language="xml">
|
||||
<![CDATA[<gfe:cache id="client-cache"/>
|
||||
|
||||
<gfe:pool id="client-pool" subscription-enabled="true" >
|
||||
<!--configure server or locator here required to address the cache server -->
|
||||
</gfe:pool>
|
||||
|
||||
<gfe:client-region id="test" cache-ref="client-cache" pool-name="client-pool"/>
|
||||
|
||||
<gfe:cq-listener-container id="queryListenerContainer" cache="client-cache"
|
||||
pool-name="client-pool"/>
|
||||
|
||||
<int-gfe:cq-inbound-channel-adapter id="inputChannel"
|
||||
cq-listener-container="queryListenerContainer"
|
||||
query="select * from /test"/>
|
||||
]]>
|
||||
</programlisting>
|
||||
|
||||
In the above configuration, we are creating a GemFire client cache
|
||||
(recall a cache server is required for this implementation and its address is configured as a sub-element of the pool), a client region and a <classname>ContinuousQueryListenerContainer</classname>
|
||||
using Spring GemFire. The continuous query inbound channel adapter requires a <code>cq-listener-container</code> attribute which contains a reference to the <classname>ContinuousQueryListenerContainer</classname>. Optionally,
|
||||
it accepts an <code>expression</code> attribute which uses SpEL to transform the <code>CqEvent</code> or extract an individual property as needed. The cq-inbound-channel-adapter provides a
|
||||
<code>query-events</code> attribute, containing a comma separated list of event types for which a message will be produced on the input channel. Available event types are CREATED, UPDATED, DESTROYED,
|
||||
REGION_DESTROYED, REGION_INVALIDATED. CREATED and UPDATED are enabled by default. Additional optional attributes include, <code>query-name</code> which provides an optional query name, and
|
||||
<code>expression</code> which works as described in the above section, and <code>durable</code> - a boolean value indicating if the query is durable (false by default).
|
||||
Note that this adapter conforms to Spring integration conventions.
|
||||
If no <code>channel</code> attribute is provided, the channel will be created from the <code>id</code> attribute. This adapter also supports an <code>error-channel</code>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Outbound Channel Adapter</title>
|
||||
<para>
|
||||
The <emphasis>outbound-channel-adapter</emphasis> writes cache entries mapped from the message payload. In its simplest form, it expects a
|
||||
payload of type <classname>java.util.Map</classname> and puts the map entries into its configured region.
|
||||
|
||||
<programlisting language="xml">
|
||||
<![CDATA[<int-gfe:outbound-channel-adapter id="cacheChannel" region="region"/>]]>
|
||||
|
||||
</programlisting>
|
||||
|
||||
Given the above configuration, an exception will be thrown if the payload is not a Map. Additionally, the outbound channel adapter can be configured to create a
|
||||
map of cache entries using SpEL of course.
|
||||
|
||||
<programlisting language="xml">
|
||||
<![CDATA[<int-gfe:outbound-channel-adapter id="cacheChannel" region="region">
|
||||
<int-gfe:cache-entries>
|
||||
<entry key="payload.toUpperCase()" value="payload.toLowerCase()"/>
|
||||
<entry key="'foo'" value="'bar'"/>
|
||||
</int-gfe:cache-entries>
|
||||
</int-gfe:outbound-channel-adapter>
|
||||
]]>
|
||||
</programlisting>
|
||||
In the above configuration, the inner element <code>cache-entries</code> is semantically equivalent to Spring 'map' element. The adapter interprets the <code>key</code> and
|
||||
<code>value</code> attributes as SpEL expressions with the message as the evaluation context. Note that this contain
|
||||
arbitrary cache entries (not only those derived from the message) and that literal values must be enclosed in single quotes. In the above example, if the message sent to
|
||||
<code>cacheChannel</code> has a String payload with a value "Hello", two entries <code>[HELLO:hello, foo:bar]</code> will be written (created or updated) in the cache region.
|
||||
This adapter also supports the <code>order</code> attribute which may be useful if it is bound to a PublishSubscribeChannel.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="gemfire-message-store">
|
||||
<title>Gemfire Message Store</title>
|
||||
|
||||
<para>
|
||||
As described in EIP, a <ulink url="http://www.eaipatterns.com/MessageStore.html">Message Store</ulink> allows you to persist Messages.
|
||||
This can be very useful when dealing with components that have a capability to buffer messages
|
||||
(<emphasis>QueueChannel, Aggregator, Resequencer</emphasis>, etc.) if reliability is a concern.
|
||||
In Spring Integration, the MessageStore strategy also provides the foundation for the
|
||||
<ulink url="http://www.eaipatterns.com/StoreInLibrary.html">ClaimCheck</ulink> pattern, which is described in EIP as well.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration's Gemfire module provides the <classname>GemfireMessageStore</classname> which is an implementation of both the
|
||||
the <classname>MessageStore</classname> strategy (mainly used by the <emphasis>QueueChannel</emphasis> and <emphasis>ClaimCheck</emphasis>
|
||||
patterns) and the <classname>MessageGroupStore</classname> strategy (mainly used by the <emphasis>Aggregator</emphasis> and
|
||||
<emphasis>Resequencer</emphasis> patterns).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<programlisting lang="xml"><![CDATA[<bean id="gemfireMessageStore" class="org.springframework.integration.gemfire.store.GemfireMessageStore">
|
||||
<constructor-arg ref="myCache"/>
|
||||
</bean>
|
||||
|
||||
<bean id="myCache" class="org.springframework.data.gemfire.CacheFactoryBean"/>
|
||||
|
||||
<int:channel id="somePersistentQueueChannel">
|
||||
<int:queue message-store="gemfireMessageStore"/>
|
||||
<int:channel>
|
||||
|
||||
<int:aggregator input-channel="inputChannel" output-channel="outputChannel"
|
||||
message-store="gemfireMessageStore"/>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Above is a sample <classname>GemfireMessageStore</classname> configuration that shows its usage by a <emphasis>QueueChannel</emphasis>
|
||||
and an <emphasis>Aggregator</emphasis>. As you can see it is a simple bean configuration, and it expects a
|
||||
<classname>GemFireCache</classname> (created by <classname>CacheFactoryBean</classname>) as a constructor argument.
|
||||
</para>
|
||||
</section>
|
||||
</chapter>
|
||||
106
src/reference/docbook/groovy.xml
Normal file
@@ -0,0 +1,106 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section version="5.0" xml:id="groovy" xmlns="http://docbook.org/ns/docbook"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:ns5="http://www.w3.org/1999/xhtml"
|
||||
xmlns:ns4="http://www.w3.org/1998/Math/MathML"
|
||||
xmlns:ns3="http://www.w3.org/2000/svg"
|
||||
xmlns:ns="http://docbook.org/ns/docbook">
|
||||
<title>Groovy support</title>
|
||||
|
||||
<para>In Spring Integration 2.0 we added Groovy support allowing you to
|
||||
use the Groovy scripting language to provide the logic for
|
||||
various integration components similar to the way the Spring Expression Language
|
||||
(SpEL) is supported for routing, transformation and other integration
|
||||
concerns. For more information about Groovy please refer to the Groovy
|
||||
documentation which you can find
|
||||
on the <ulink url="http://groovy.codehaus.org">project website</ulink></para>
|
||||
|
||||
<section id="groovy-config">
|
||||
<title>Groovy configuration</title>
|
||||
<para>
|
||||
With Spring Integration 2.1, Groovy Support's configuration namespace
|
||||
is an extension of Spring Integration's Scripting Support and shares the core configuration
|
||||
and behavior described in detail in the
|
||||
<xref linkend="scripting">Scripting Support</xref> section. Even though Groovy scripts are
|
||||
well supported by generic Scripting Support, Groovy Support provides the
|
||||
<emphasis>Groovy</emphasis> configuration namespace which is backed by the Spring Framework's
|
||||
<classname>org.springframework.scripting.groovy.GroovyScriptFactory</classname> and related components,
|
||||
offering extended capabilities for using Groovy. Below are a couple of sample configurations:</para>
|
||||
<para><emphasis>Filter</emphasis> <programlisting language="xml"><int:filter input-channel="referencedScriptInput">
|
||||
<int-groovy:script location="some/path/to/groovy/file/GroovyFilterTests.groovy"/>
|
||||
</int:filter>
|
||||
|
||||
<int:filter input-channel="inlineScriptInput">
|
||||
<int-groovy:script><![CDATA[
|
||||
return payload == 'good'
|
||||
]]></int-groovy:script>
|
||||
</int:filter></programlisting>
|
||||
As the above examples show, the configuration looks identical to the general Scripting Support configuration. The only
|
||||
difference is the use of the Groovy namespace as indicated in the examples by the <emphasis>int-groovy</emphasis> namespace prefix.
|
||||
Also note that the <code>lang</code> attribute on the <code><script></code> tag is not valid in this namespace.
|
||||
</para>
|
||||
|
||||
|
||||
<para><emphasis>Groovy object customization</emphasis> </para>
|
||||
|
||||
<para>
|
||||
If you need to customize the Groovy object itself, beyond setting variables, you can reference
|
||||
a bean that implements <classname>org.springframework.scripting.groovy.GroovyObjectCustomizer</classname> via the
|
||||
<code>customizer</code> attribute. For example, this might be useful if you want to implement a domain-specific
|
||||
language (DSL) by modifying the MetaClass and registering functions to be available within the script:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="groovyChannel">
|
||||
<int-groovy:script location="foo/SomeScript.groovy" customizer="groovyCustomizer"/>
|
||||
</int:service-activator>
|
||||
|
||||
<beans:bean id="groovyCustomizer" class="org.foo.MyGroovyObjectCustomizer"/>]]></programlisting>
|
||||
|
||||
Setting a custom GroovyObjectCustomizer is not mutually exclusive with <code><variable></code> sub-elements or
|
||||
the <code>script-variable-generator</code> attribute. It can also be provided when defining an inline script.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="groovy-control-bus">
|
||||
<title>Control Bus</title>
|
||||
|
||||
<para>As described in (<ulink
|
||||
url="http://www.eaipatterns.com/ControlBus.html">EIP</ulink>), the idea
|
||||
behind the Control Bus is that the same messaging system can be used for
|
||||
monitoring and managing the components within the framework as is used for
|
||||
"application-level" messaging. In Spring Integration we build upon the
|
||||
adapters described above so that it's possible to send Messages as a means
|
||||
of invoking exposed operations. One option for those operations is Groovy scripts.
|
||||
<programlisting language="xml"> <int-groovy:control-bus input-channel="operationChannel"/></programlisting></para>
|
||||
|
||||
<para>The Control Bus has an input channel that can be accessed for
|
||||
invoking operations on the beans in the application context.</para>
|
||||
|
||||
<para>The Groovy Control Bus executes messages on the input channel as
|
||||
Groovy scripts. It takes a message, compiles the body to a Script,
|
||||
customizes it with a <classname>GroovyObjectCustomizer</classname>, and then executes it. The
|
||||
Control Bus' customizer exposes all the beans in the application context
|
||||
that are annotated with <code>@ManagedResource</code>, implement Spring's
|
||||
<classname>Lifecycle</classname> interface or extend Spring's <classname>CustomizableThreadCreator</classname> base class
|
||||
(e.g. several of the <classname>TaskExecutor</classname> and <classname>TaskScheduler</classname> implementations).</para>
|
||||
<para>
|
||||
<important>
|
||||
Be careful about using managed beans with custom scopes (e.g. 'request') in the Control Bus' command scripts, especially
|
||||
inside an <emphasis>async</emphasis> message flow. If <emphasis>The Control Bus' customizer</emphasis> can't expose a bean
|
||||
from the application context, it skips that bean. For example, if a custom scope's context is not established, the attempt
|
||||
to get a bean within that scope will trigger a <classname>BeanCreationException</classname>. In that case, such a bean
|
||||
will be ignored, and the customizer will continue with other beans.
|
||||
</important>
|
||||
</para>
|
||||
<para>
|
||||
If you need to further customize the Groovy objects, you can also provide a reference to a bean
|
||||
that implements <classname>org.springframework.scripting.groovy.GroovyObjectCustomizer</classname> via
|
||||
the <code>customizer</code> attribute.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-groovy:control-bus input-channel="input"
|
||||
output-channel="output"
|
||||
customizer="groovyCustomizer"/>
|
||||
|
||||
<beans:bean id="groovyCustomizer" class="org.foo.MyGroovyObjectCustomizer"/>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
10
src/reference/docbook/history.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<appendix xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="history"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude">
|
||||
<title>Change History</title>
|
||||
|
||||
<xi:include href="./changes-1.0-2.0.xml"/>
|
||||
<xi:include href="./changes-2.0-2.1.xml"/>
|
||||
|
||||
</appendix>
|
||||
381
src/reference/docbook/http.xml
Normal file
@@ -0,0 +1,381 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="http"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>HTTP Support</title>
|
||||
|
||||
<section id="http-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
The HTTP support allows for the execution of HTTP requests and the processing of inbound HTTP requests. Because interaction over HTTP is always synchronous, even if all that is returned is a 200 status code, the HTTP support consists of two gateway implementations:
|
||||
<classname>HttpInboundEndpoint</classname> and <classname>HttpRequestExecutingMessageHandler</classname>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="http-inbound">
|
||||
<title>Http Inbound Gateway</title>
|
||||
<para>
|
||||
To receive messages over HTTP you need to use an HTTP inbound Channel Adapter or Gateway. In common with the HttpInvoker
|
||||
support the HTTP inbound adapters need to be deployed within a servlet container. The easiest way to do this is to provide a servlet
|
||||
definition in <emphasis>web.xml</emphasis>, see
|
||||
<xref linkend="httpinvoker-inbound"/> for further details. Below is an example bean definition for a simple HTTP inbound endpoint.
|
||||
<programlisting language="xml"><![CDATA[<bean id="httpInbound"
|
||||
class="org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway">
|
||||
<property name="requestChannel" ref="httpRequestChannel" />
|
||||
<property name="replyChannel" ref="httpReplyChannel" />
|
||||
</bean>]]></programlisting>
|
||||
The <classname>HttpRequestHandlingMessagingGateway</classname> accepts a list of <interfacename>HttpMessageConverter</interfacename> instances or else
|
||||
relies on a default list. The converters allow
|
||||
customization of the mapping from <interfacename>HttpServletRequest</interfacename> to <interfacename>Message</interfacename>. The default converters
|
||||
encapsulate simple strategies, which for
|
||||
example will create a String message for a <emphasis>POST</emphasis> request where the content type starts with "text", see the Javadoc for
|
||||
full details.
|
||||
</para>
|
||||
<para>Starting with this release MultiPart File support was implemented. If the request has been wrapped as a
|
||||
<emphasis>MultipartHttpServletRequest</emphasis>, when using the default converters, that request will be converted
|
||||
to a Message payload that is a MultiValueMap containing values that may be byte arrays, Strings, or instances of
|
||||
Spring's <interfacename>MultipartFile</interfacename> depending on the content type of the individual parts.
|
||||
<note>
|
||||
The HTTP inbound Endpoint will locate a MultipartResolver in the context if one exists with the bean name
|
||||
"multipartResolver" (the same name expected by Spring's DispatcherServlet). If it does in fact locate that
|
||||
bean, then the support for MultipartFiles will be enabled on the inbound request mapper. Otherwise, it will
|
||||
fail when trying to map a multipart-file request to a Spring Integration Message. For more on Spring's
|
||||
support for MultipartResolvers, refer to the <ulink url="http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html#mvc-multipart">Spring Reference Manual</ulink>.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
In sending a response to the client there are a number of ways to customize the behavior of the gateway. By default the gateway will
|
||||
simply acknowledge that the request was received by sending a 200 status code back. It is possible to customize this response by providing a
|
||||
'viewName' to be resolved by the Spring MVC <interfacename>ViewResolver</interfacename>.
|
||||
In the case that the gateway should expect a reply to the <interfacename>Message</interfacename> then setting the <property>expectReply</property> flag
|
||||
(constructor argument) will cause
|
||||
the gateway to wait for a reply <interfacename>Message</interfacename> before creating an HTTP response. Below is an example of a gateway
|
||||
configured to serve as a Spring MVC Controller with a view name. Because of the constructor arg value of TRUE, it wait for a reply. This also shows
|
||||
how to customize the HTTP methods accepted by the gateway, which
|
||||
are <emphasis>POST</emphasis> and <emphasis>GET</emphasis> by default.
|
||||
<programlisting language="xml"><![CDATA[<bean id="httpInbound"
|
||||
class="org.springframework.integration.http.inbound.HttpRequestHandlingController">
|
||||
<constructor-arg value="true" /> <!-- indicates that a reply is expected -->
|
||||
<property name="requestChannel" ref="httpRequestChannel" />
|
||||
<property name="replyChannel" ref="httpReplyChannel" />
|
||||
<property name="viewName" value="jsonView" />
|
||||
<property name="supportedMethodNames" >
|
||||
<list>
|
||||
<value>GET</value>
|
||||
<value>DELETE</value>
|
||||
</list>
|
||||
</property>
|
||||
</bean>]]></programlisting>
|
||||
The reply message will be available in the Model map. The key that is used
|
||||
for that map entry by default is 'reply', but this can be overridden by setting the
|
||||
'replyKey' property on the endpoint's configuration.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="http-outbound">
|
||||
<title>Http Outbound Gateway</title>
|
||||
|
||||
<para>
|
||||
To configure the <classname>HttpRequestExecutingMessageHandler</classname> write a bean definition like this:
|
||||
<programlisting language="xml"><![CDATA[<bean id="httpOutbound"
|
||||
class="org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler">
|
||||
<constructor-arg value="http://localhost:8080/example" />
|
||||
<property name="outputChannel" ref="responseChannel" />
|
||||
</bean>]]></programlisting>
|
||||
This bean definition will execute HTTP requests by delegating to a <classname>RestTemplate</classname>. That template in turn delegates
|
||||
to a list of HttpMessageConverters to generate the HTTP request body from the Message payload. You can configure those converters as well
|
||||
as the ClientHttpRequestFactory instance to use:
|
||||
<programlisting language="xml"><![CDATA[<bean id="httpOutbound"
|
||||
class="org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler">
|
||||
<constructor-arg value="http://localhost:8080/example" />
|
||||
<property name="outputChannel" ref="responseChannel" />
|
||||
<property name="messageConverters" ref="messageConverterList" />
|
||||
<property name="requestFactory" ref="customRequestFactory" />
|
||||
</bean>]]></programlisting>
|
||||
By default the HTTP request will be generated using an instance of <classname>SimpleClientHttpRequestFactory</classname> which uses the JDK
|
||||
<classname>HttpURLConnection</classname>. Use of the Apache Commons HTTP Client is also supported through the provided
|
||||
<classname>CommonsClientHttpRequestFactory</classname> which can be injected as shown above.
|
||||
</para>
|
||||
<para>
|
||||
<note>
|
||||
In the case of the Outbound Gateway, the reply message produced by the gateway will contain all Message Headers present in the request message.
|
||||
</note>
|
||||
</para>
|
||||
<para><emphasis>Cookies</emphasis></para>
|
||||
<para>
|
||||
Basic cookie support is provided by the <emphasis>transfer-cookies</emphasis> attribute on the outbound gateway. When
|
||||
set to true (default is false), a <emphasis>Set-Cookie</emphasis> header received from the server in a response will be
|
||||
converted to <emphasis>Cookie</emphasis> in the reply message. This header will then be used
|
||||
on subsequent sends. This enables simple stateful interactions, such as...
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>...->logonGateway->...->doWorkGateway->...->logoffGateway->...</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
If <emphasis>transfer-cookies</emphasis> is false, any <emphasis>Set-Cookie</emphasis> header received will
|
||||
remain as <emphasis>Set-Cookie</emphasis> in the reply message, and will be dropped on subsequent sends.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="http-namespace">
|
||||
<title>HTTP Namespace Support</title>
|
||||
<para>
|
||||
Spring Integration provides an "http" namespace and schema definition. To include it in your
|
||||
configuration, simply provide the following URI within a namespace declaration:
|
||||
'http://www.springframework.org/schema/integration/http'. The schema location should then map to
|
||||
'http://www.springframework.org/schema/integration/http/spring-integration-http.xsd'.
|
||||
</para>
|
||||
<para>
|
||||
To configure an inbound http channel adapter which is an instance of <classname>HttpInboundEndpoint</classname> configured
|
||||
not to expect a response.
|
||||
<programlisting language="xml"><![CDATA[<int-http:inbound-channel-adapter id="httpChannelAdapter" channel="requests"
|
||||
supported-methods="PUT, DELETE"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To configure an inbound http gateway which expects a response.
|
||||
<programlisting language="xml"><![CDATA[ <int-http:inbound-gateway id="inboundGateway"
|
||||
request-channel="requests"
|
||||
reply-channel="responses"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To configure the outbound gateway you can use the namespace support as well. The following code snippet shows the different configuration options for an outbound Http gateway. Most importantly, notice that the 'http-method' and 'expected-response-type' are provided. Those are two of the most commonly configured values. The
|
||||
default http-method is POST, and the default response type is <emphasis>null</emphasis>. With a null response type, the payload of the reply Message would only
|
||||
contain the status code (e.g. 200) as long as it's a successful status (non-successful status codes will throw Exceptions). If you are expecting a different
|
||||
type, such as a <classname>String</classname>, then provide that fully-qualified class name as shown below.
|
||||
<programlisting language="xml"><![CDATA[<int-http:outbound-gateway id="example"
|
||||
request-channel="requests"
|
||||
url="http://localhost/test"
|
||||
http-method="POST"
|
||||
extract-request-payload="false"
|
||||
expected-response-type="java.lang.String"
|
||||
charset="UTF-8"
|
||||
request-factory="requestFactory"
|
||||
request-timeout="1234"
|
||||
reply-channel="replies"/>]]></programlisting>
|
||||
</para>
|
||||
<para>If your outbound adapter is to be used in a unidirectional way, then you can use an outbound-channel-adapter instead. This means that
|
||||
a successful response will simply execute without sending any Messages to a reply channel. In the case of any non-successful response
|
||||
status code, it will throw an exception. The configuration looks very similar to the gateway:
|
||||
<programlisting language="xml"><![CDATA[<int-http:outbound-channel-adapter id="example"
|
||||
url="http://localhost/example"
|
||||
http-method="GET"
|
||||
channel="requests"
|
||||
charset="UTF-8"
|
||||
extract-payload="false"
|
||||
expected-response-type="java.lang.String"
|
||||
request-factory="someRequestFactory"
|
||||
order="3"
|
||||
auto-startup="false"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Mapping URI variables</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
If your URL contains URI variables you can map them using <code>uri-variable</code> sub element in
|
||||
<emphasis>Http Outbound Gateway</emphasis> configuration.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-http:outbound-gateway id="trafficGateway"
|
||||
url="http://local.yahooapis.com/trafficData?appid=YdnDemo&zip={zipCode}"
|
||||
request-channel="trafficChannel"
|
||||
http-method="GET"
|
||||
expected-response-type="java.lang.String">
|
||||
<int-http:uri-variable name="zipCode" expression="payload.getZip()"/>
|
||||
</int-http:outbound-gateway>]]></programlisting>
|
||||
|
||||
The <code>uri-variable</code> defines two attributes <code>expression</code> and <code>value</code>. You generally use
|
||||
the <code>value</code> attribute for literal values, but if the value you are trying to inject is dynamic and requires
|
||||
access to Message data you can use a SpEL expression via the <code>expression</code> attribute. In the above configuration
|
||||
the <code>getZip()</code> method will be invoked on the payload object of the Message and the result of that
|
||||
method will be used as the value for URI variable named 'zipCode'.
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="http-proxy">
|
||||
<title>HTTP Proxy configuration</title>
|
||||
|
||||
<para>
|
||||
If you are behind a proxy and need to configure proxy settings for HTTP outbound adapters and/or
|
||||
gateways, you can apply one of two approaches. In most cases, you can rely on the standard Java
|
||||
System Properties that control the proxy settings. Otherwise, you can explicitly configure a
|
||||
Spring bean for the HTTP client request factory instance.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Standard Java Proxy configuration</emphasis>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
There are 3 System Properties you can set to configure the proxy settings that will be used by the HTTP protocol handler:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>http.proxyHost</emphasis> - the host name of the proxy server. </para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para><emphasis>http.proxyPort</emphasis> - the port number, the default value being 80. </para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para><emphasis>http.nonProxyHosts</emphasis> - a list of hosts that should be reached directly,
|
||||
bypassing the proxy. This is a list of patterns separated by '|'. The patterns may start or end with a '*' for wildcards. Any host matching one of these patterns will be reached through a direct connection instead of through a proxy. </para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
And for HTTPS:
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>https.proxyHost</emphasis> - the host name of the proxy server. </para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para><emphasis>https.proxyPort</emphasis> - the port number, the default value being 80. </para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
For more information please refer to this document: http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Spring's SimpleClientHttpRequestFactory</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
If for any reason, you need more explicit control over the proxy configuration, you can use Spring's
|
||||
<classname>SimpleClientHttpRequestFactory</classname> and configure its 'proxy' property as such:
|
||||
<programlisting language="xml"><![CDATA[<bean id="requestFactory"
|
||||
class="org.springframework.http.client.SimpleClientHttpRequestFactory">
|
||||
<property name="proxy">
|
||||
<bean id="proxy" class="java.net.Proxy">
|
||||
<constructor-arg>
|
||||
<util:constant static-field="java.net.Proxy.Type.HTTP"/>
|
||||
</constructor-arg>
|
||||
<constructor-arg>
|
||||
<bean class="java.net.InetSocketAddress">
|
||||
<constructor-arg value="123.0.0.1"/>
|
||||
<constructor-arg value="8080"/>
|
||||
</bean>
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
</property>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="http-header-mapping">
|
||||
<title> HTTP Header Mappings</title>
|
||||
<para>
|
||||
Spring Integration provides support for Http Header mapping for both HTTP Request and HTTP Responses.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
By default all standard Http Headers as defined here
|
||||
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields will be mapped from the message to HTTP request/response headers without
|
||||
further configuration.
|
||||
However if you do need further customization you may provide additional configuration via convenient namespace support.
|
||||
You can provide a comma-separated list of header names, and you can also include simple patterns with the '*' character acting as a wildcard.
|
||||
If you do provide such values, it will override the default behavior. Basically, it assumes you are in complete control at that point.
|
||||
However, if you do want to include all of the standard HTTP headers, you can use the shortcut patterns: HTTP_REQUEST_HEADERS and
|
||||
HTTP_RESPONSE_HEADERS. Here are some examples:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-http:outbound-gateway id="httpGateway"
|
||||
url="http://localhost/test2"
|
||||
mapped-request-headers="foo, bar"
|
||||
mapped-response-headers="X-*, HTTP_RESPONSE_HEADERS"
|
||||
channel="someChannel"/>
|
||||
|
||||
<int-http:outbound-channel-adapter id="httpAdapter"
|
||||
url="http://localhost/test2"
|
||||
mapped-request-headers="foo, bar, HTTP_REQUEST_HEADERS"
|
||||
channel="someChannel"/>]]></programlisting>
|
||||
|
||||
The adapters and gateways will use the <classname>DefaultHttpHeaderMapper</classname> which now provides
|
||||
two static factory methods for "inbound" and "outbound" adapters so that the proper direction can be
|
||||
applied (mapping HTTP requests/responses IN/OUT as appropriate).
|
||||
</para>
|
||||
<para>
|
||||
If further customization is required you can also configure a <classname>DefaultHttpHeaderMapper</classname> independently
|
||||
and inject it into the adapter via the <code>header-mapper</code> attribute.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-http:outbound-gateway id="httpGateway"
|
||||
url="http://localhost/test2"
|
||||
header-mapper="headerMapper"
|
||||
channel="someChannel"/>
|
||||
|
||||
<bean id="headerMapper" class="org.springframework.integration.http.support.DefaultHttpHeaderMapper">
|
||||
<property name="inboundHeaderNames" value="foo*, *bar, baz"/>
|
||||
<property name="outboundHeaderNames" value="a*b, d"/>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
<para>Of course, you can even implement the HeaderMapper strategy interface directly and provide a reference to that
|
||||
if you need to do something other than what the <classname>DefaultHttpHeaderMapper</classname> supports.</para>
|
||||
</section>
|
||||
|
||||
<section id="http-samples">
|
||||
<title>HTTP Samples</title>
|
||||
<section id="multipart-rest-inbound">
|
||||
<title>Multipart HTTP request - RestTemplate (client) and Http Inbound Gateway (server)</title>
|
||||
<para>
|
||||
This example demonstrates how simple it is to send a Multipart HTTP request via Spring's RestTemplate and receive
|
||||
it with a Spring Integration HTTP Inbound Adapter. All we are doing is creating a <classname>MultiValueMap</classname> and
|
||||
populating it with multi-part data. The <classname>RestTemplate</classname> will take care of the rest (no pun intended) by
|
||||
converting it to a <classname>MultipartHttpServletRequest</classname> . This particular client will send a multipart HTTP Request
|
||||
which contains the name of the company as well as an image file with the company logo.
|
||||
<programlisting language="java"><![CDATA[RestTemplate template = new RestTemplate();
|
||||
String uri = "http://localhost:8080/multipart-http/inboundAdapter.htm";
|
||||
Resource s2logo =
|
||||
new ClassPathResource("org/springframework/samples/multipart/spring09_logo.png");
|
||||
MultiValueMap map = new LinkedMultiValueMap();
|
||||
map.add("company", "SpringSource");
|
||||
map.add("company-logo", s2logo);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(new MediaType("multipart", "form-data"));
|
||||
HttpEntity request = new HttpEntity(map, headers);
|
||||
ResponseEntity<?> httpResponse = template.exchange(uri, HttpMethod.POST, request, null);]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
That is all for the client.
|
||||
</para>
|
||||
<para>
|
||||
On the server side we have the following configuration:
|
||||
<programlisting language="xml"><![CDATA[<int-http:inbound-channel-adapter id="httpInboundAdapter"
|
||||
channel="receiveChannel"
|
||||
name="/inboundAdapter.htm"
|
||||
supported-methods="GET, POST" />
|
||||
|
||||
<int:channel id="receiveChannel"/>
|
||||
|
||||
<int:service-activator input-channel="receiveChannel">
|
||||
<bean class="org.springframework.integration.samples.multipart.MultipartReceiver"/>
|
||||
</int:service-activator>
|
||||
|
||||
<bean id="multipartResolver"
|
||||
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The 'httpInboundAdapter' will receive the request, convert it to a <classname>Message</classname> with a payload
|
||||
that is a <classname>LinkedMultiValueMap</classname>. We then are parsing that in the 'multipartReceiver' service-activator;
|
||||
<programlisting language="java"><![CDATA[public void receive(LinkedMultiValueMap<String, Object> multipartRequest){
|
||||
System.out.println("### Successfully received multipart request ###");
|
||||
for (String elementName : multipartRequest.keySet()) {
|
||||
if (elementName.equals("company")){
|
||||
System.out.println("\t" + elementName + " - " +
|
||||
((String[]) multipartRequest.getFirst("company"))[0]);
|
||||
}
|
||||
else if (elementName.equals("company-logo")){
|
||||
System.out.println("\t" + elementName + " - as UploadedMultipartFile: " +
|
||||
((UploadedMultipartFile) multipartRequest.getFirst("company-logo")).
|
||||
getOriginalFilename());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
]]></programlisting>
|
||||
You should see the following output:
|
||||
<programlisting language="xml"><![CDATA[### Successfully received multipart request ###
|
||||
company - SpringSource
|
||||
company-logo - as UploadedMultipartFile: spring09_logo.png]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
</chapter>
|
||||
BIN
src/reference/docbook/images/bank-router.jpg
Normal file
|
After Width: | Height: | Size: 6.5 KiB |
BIN
src/reference/docbook/images/cafe-eip.png
Normal file
|
After Width: | Height: | Size: 112 KiB |
BIN
src/reference/docbook/images/chain.png
Normal file
|
After Width: | Height: | Size: 41 KiB |
BIN
src/reference/docbook/images/channel.jpg
Normal file
|
After Width: | Height: | Size: 28 KiB |
BIN
src/reference/docbook/images/gateway.jpg
Normal file
|
After Width: | Height: | Size: 3.6 KiB |
BIN
src/reference/docbook/images/handler-endpoint.jpg
Normal file
|
After Width: | Height: | Size: 31 KiB |
BIN
src/reference/docbook/images/loan-broker-eip.png
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
src/reference/docbook/images/logo.png
Normal file
|
After Width: | Height: | Size: 9.4 KiB |
BIN
src/reference/docbook/images/message.jpg
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
src/reference/docbook/images/quotes-aggregator.jpg
Normal file
|
After Width: | Height: | Size: 6.3 KiB |
BIN
src/reference/docbook/images/router.jpg
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
src/reference/docbook/images/source-endpoint.jpg
Normal file
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 19 KiB |
BIN
src/reference/docbook/images/target-endpoint.jpg
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
src/reference/docbook/images/tickmark.png
Normal file
|
After Width: | Height: | Size: 4.0 KiB |
169
src/reference/docbook/index.xml
Normal file
@@ -0,0 +1,169 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<book xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="spring-integration-reference"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<bookinfo>
|
||||
<title>Spring Integration Reference Manual</title>
|
||||
<titleabbrev>Spring Integration ${version}</titleabbrev>
|
||||
<productname>Spring Integration</productname>
|
||||
<releaseinfo>${version}</releaseinfo>
|
||||
|
||||
<!-- TODO: this isn't showing up. -->
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/logo.png"
|
||||
format="PNG" align="center"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/logo.png" format="PNG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
<!-- END TODO -->
|
||||
|
||||
<authorgroup>
|
||||
<author>
|
||||
<firstname>Mark</firstname>
|
||||
<surname>Fisher</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Marius</firstname>
|
||||
<surname>Bogoevici</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Iwein</firstname>
|
||||
<surname>Fuld</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Jonas</firstname>
|
||||
<surname>Partner</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Oleg</firstname>
|
||||
<surname>Zhurakousky</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Gary</firstname>
|
||||
<surname>Russell</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Dave</firstname>
|
||||
<surname>Syer</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Josh</firstname>
|
||||
<surname>Long</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>David</firstname>
|
||||
<surname>Turanski</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Gunnar</firstname>
|
||||
<surname>Hillert</surname>
|
||||
</author>
|
||||
<author>
|
||||
<firstname>Artem</firstname>
|
||||
<surname>Bilan</surname>
|
||||
</author>
|
||||
</authorgroup>
|
||||
|
||||
<legalnotice><para>© SpringSource Inc., 2011</para></legalnotice>
|
||||
</bookinfo>
|
||||
|
||||
<toc></toc>
|
||||
|
||||
<xi:include href="./preface.xml"/>
|
||||
|
||||
<part id="whats-new-part">
|
||||
<title>What's new?</title>
|
||||
<partintro id="spring-integration-intro">
|
||||
<para>
|
||||
For those who are already familiar with Spring Integration, this chapter
|
||||
provides a brief overview of the new features of version 2.1. If you are
|
||||
interested in the changes and features, that were introduced in earlier
|
||||
versions, please take a look at chapter:
|
||||
|
||||
<xref linkend="history"/>
|
||||
|
||||
</para>
|
||||
</partintro>
|
||||
<xi:include href="./whats-new.xml"/>
|
||||
</part>
|
||||
|
||||
<part id="spring-integration-introduction">
|
||||
<title>Overview of Spring Integration Framework</title>
|
||||
<partintro id="spring-integration-intro">
|
||||
<para>
|
||||
Spring Integration provides an extension of the Spring programming model to support the well-known
|
||||
<ulink url="http://www.eaipatterns.com/">Enterprise Integration Patterns</ulink>.
|
||||
It enables lightweight messaging <emphasis>within</emphasis> Spring-based applications and supports
|
||||
integration with external systems via declarative adapters.
|
||||
Those adapters provide a higher-level of abstraction over Spring's support for remoting, messaging, and scheduling.
|
||||
Spring Integration's primary goal is to provide a simple model for building enterprise integration solutions
|
||||
while maintaining the separation of concerns that is essential for producing maintainable, testable code.
|
||||
</para>
|
||||
</partintro>
|
||||
<xi:include href="./overview.xml"/>
|
||||
</part>
|
||||
|
||||
<part id="spring-integration-core-messaging">
|
||||
<title>Core Messaging</title>
|
||||
<partintro id="spring-integration-core-msg">
|
||||
<para>This section covers all aspects of the core messaging API in Spring Integration.
|
||||
Here you will learn about Messages, Message Channels, and Message Endpoints.
|
||||
Many of the Enterprise Integration Patterns are covered here as well,
|
||||
such as Filters, Routers, Transformers, Service-Activators, Splitters, and Aggregators.
|
||||
The section also contains material about System Management, including the Control Bus and Message History support.
|
||||
</para>
|
||||
</partintro>
|
||||
|
||||
<xi:include href="./messaging-channels.xml"/>
|
||||
<xi:include href="./message-construction.xml"/>
|
||||
<xi:include href="./message-routing.xml"/>
|
||||
<xi:include href="./message-transformation.xml"/>
|
||||
<xi:include href="./messaging-endpoints.xml"/>
|
||||
<xi:include href="./system-management.xml"/>
|
||||
</part>
|
||||
<part id="spring-integration-adapters">
|
||||
<title>Integration Adapters</title>
|
||||
<partintro id="spring-integration-adapters">
|
||||
<para>This section covers the various Channel Adapters and Messaging Gateways provided
|
||||
by Spring Integration to support Message-based communication with external systems.
|
||||
</para>
|
||||
</partintro>
|
||||
<xi:include href="./amqp.xml"/>
|
||||
<xi:include href="./event.xml"/>
|
||||
<xi:include href="./feed.xml"/>
|
||||
<xi:include href="./file.xml"/>
|
||||
<xi:include href="./ftp.xml"/>
|
||||
<xi:include href="./gemfire.xml"/>
|
||||
<xi:include href="./http.xml"/>
|
||||
<xi:include href="./ip.xml"/>
|
||||
<xi:include href="./jdbc.xml"/>
|
||||
<xi:include href="./jms.xml"/>
|
||||
<xi:include href="./mail.xml"/>
|
||||
<xi:include href="./mongodb.xml"/>
|
||||
<xi:include href="./redis.xml"/>
|
||||
<xi:include href="./resource.xml"/>
|
||||
<xi:include href="./rmi.xml"/>
|
||||
<xi:include href="./sftp.xml"/>
|
||||
<xi:include href="./stream.xml"/>
|
||||
<xi:include href="./twitter.xml"/>
|
||||
<xi:include href="./ws.xml"/>
|
||||
<xi:include href="./xml.xml"/>
|
||||
<xi:include href="./xmpp.xml"/>
|
||||
</part>
|
||||
<part id="spring-integration-appendices">
|
||||
<title>Appendices</title>
|
||||
<partintro id="spring-integration-adapters">
|
||||
<para>Advanced Topics and Additional Resources</para>
|
||||
</partintro>
|
||||
<xi:include href="./message-publishing.xml"/>
|
||||
<xi:include href="./transactions.xml"/>
|
||||
<xi:include href="./security.xml"/>
|
||||
<xi:include href="./samples.xml"/>
|
||||
<xi:include href="./configuration.xml"/>
|
||||
<xi:include href="./resources.xml"/>
|
||||
<xi:include href="./history.xml"/>
|
||||
</part>
|
||||
</book>
|
||||
1459
src/reference/docbook/ip.xml
Normal file
969
src/reference/docbook/jdbc.xml
Normal file
@@ -0,0 +1,969 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="jdbc"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>JDBC Support</title>
|
||||
|
||||
<para>
|
||||
Spring Integration provides Channel Adapters for receiving and sending
|
||||
messages via database queries. Through those adapters Spring Integration
|
||||
supports not only plain JDBC SQL Queries, but also Stored Procedure and
|
||||
Stored Function calls.
|
||||
</para>
|
||||
<para>
|
||||
The following JDBC components are available by default:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='jdbc-inbound-channel-adapter'>Inbound Channel Adapter</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='jdbc-outbound-channel-adapter'>Outbound Channel Adapter</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='jdbc-outbound-gateway'>Outbound Gateway</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='stored-procedure-inbound-channel-adapter'>Stored Procedure Inbound Channel Adapter</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='stored-procedure-outbound-channel-adapter'>Stored Procedure Outbound Channel Adapter</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='stored-procedure-outbound-gateway'>Stored Procedure Outbound Gateway</link></emphasis></para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
Furthermore, the Spring Integration JDBC Module also provides a
|
||||
<emphasis><link linkend='jdbc-message-store'>JDBC Message Store</link></emphasis>
|
||||
</para>
|
||||
|
||||
<section id="jdbc-inbound-channel-adapter">
|
||||
<title>Inbound Channel Adapter</title>
|
||||
|
||||
<para>The main function of an inbound Channel Adapter is to execute a SQL
|
||||
<code>SELECT</code> query and turn the result set as a message. The
|
||||
message payload is the whole result set, expressed as a
|
||||
<classname>List</classname>, and the types of the items in the list
|
||||
depend on the row-mapping strategy that is used. The default strategy is
|
||||
a generic mapper that just returns a <classname>Map</classname> for each
|
||||
row in the query result. Optionally, this can be changed by adding a reference to
|
||||
a <classname>RowMapper</classname> instance (see the
|
||||
<ulink url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html">Spring
|
||||
JDBC</ulink> documentation for more detailed information about row mapping).<note>
|
||||
<para>If you want to convert rows in the SELECT query result to
|
||||
individual messages you can use a downstream splitter.</para>
|
||||
</note></para>
|
||||
|
||||
<para>The inbound adapter also requires a reference to either
|
||||
a <classname>JdbcTemplate</classname> instance or
|
||||
a <interfacename>DataSource</interfacename>.</para>
|
||||
|
||||
<para>As well as the <code>SELECT</code> statement to generate the
|
||||
messages, the adapter above also has an <code>UPDATE</code> statement that
|
||||
is being used to mark the records as processed so that they don't show up in
|
||||
the next poll. The update can be parameterized by the list of ids from the
|
||||
original select. This is done through a naming convention by default (a
|
||||
column in the input result set called "id" is translated into a list in
|
||||
the parameter map for the update called "id"). The following example
|
||||
defines an inbound Channel Adapter with an update query and a
|
||||
<classname>DataSource</classname> reference.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:inbound-channel-adapter query="select * from item where status=2"
|
||||
channel="target" data-source="dataSource"
|
||||
update="update item set status=10 where id in (:id)" />]]></programlisting>
|
||||
<note>
|
||||
The parameters in the update query are specified with a colon (:) prefix to the name of a parameter (which in this case is an expression to be applied to each of the rows in the polled result set). This is a standard feature of the named parameter JDBC support in Spring JDBC combined with a convention (projection onto the polled result list) adopted in Spring Integration. The underlying Spring JDBC features limit the available expressions (e.g. most special characters other than period are disallowed), but since the target is usually a list of or an individual object addressable by simple bean paths this isn't unduly restrictive.
|
||||
</note> To change the parameter generation strategy you can inject a
|
||||
<classname>SqlParameterSourceFactory</classname> into the adapter to
|
||||
override the default behavior (the adapter has a
|
||||
<code>sql-parameter-source-factory</code> attribute).</para>
|
||||
|
||||
<section>
|
||||
<title>Polling and Transactions</title>
|
||||
|
||||
<para>The inbound adapter accepts a regular Spring Integration poller as
|
||||
a sub element, so for instance the frequency of the polling can be
|
||||
controlled. A very important feature of the poller for JDBC usage is the
|
||||
option to wrap the poll operation in a transaction, for example:</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:inbound-channel-adapter query="..."
|
||||
channel="target" data-source="dataSource" update="...">
|
||||
<int:poller fixed-rate="1000">
|
||||
<int:transactional/>
|
||||
</int:poller>
|
||||
</int-jdbc:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
<para><note>
|
||||
If a poller is not explicitly specified, a default value will be used (and as per normal with Spring Integration can be defined as a top level bean).
|
||||
</note>
|
||||
In this example the database is polled every 1000 milliseconds, and the update and
|
||||
select queries are both executed in the same transaction. The transaction manager
|
||||
configuration is not shown, but as long as it is aware of the data source then the
|
||||
poll is transactional. A common use case is for the downstream channels to be
|
||||
direct channels (the default), so that the endpoints are invoked in the
|
||||
same thread, and hence the same transaction. Then if any of them fail,
|
||||
the transaction rolls back and the input data is reverted to its
|
||||
original state.</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="jdbc-outbound-channel-adapter">
|
||||
<title>Outbound Channel Adapter</title>
|
||||
|
||||
<para>The outbound Channel Adapter is the inverse of the inbound: its role
|
||||
is to handle a message and use it to execute a SQL query. The message
|
||||
payload and headers are available by default as input parameters to the
|
||||
query, for instance:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:outbound-channel-adapter
|
||||
query="insert into foos (id, status, name) values (:headers[id], 0, :payload[foo])"
|
||||
data-source="dataSource"
|
||||
channel="input"/>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the example above, messages arriving on the channel labelled
|
||||
<emphasis>input</emphasis> have a payload of a map with key
|
||||
<emphasis>foo</emphasis>, so the <code>[]</code> operator dereferences
|
||||
that value from the map. The headers are also accessed as a map.
|
||||
</para>
|
||||
|
||||
<note>
|
||||
The parameters in the query above are bean property expressions on the
|
||||
incoming message (not Spring EL expressions). This behavior is part of the
|
||||
<classname>SqlParameterSource</classname>
|
||||
which is the default source created by the outbound adapter. Other
|
||||
behavior is possible in the adapter, and requires the user to inject a
|
||||
different <classname>SqlParameterSourceFactory</classname>.
|
||||
</note>
|
||||
|
||||
<para>
|
||||
The outbound adapter requires a reference to either a
|
||||
<interfacename>DataSource</interfacename> or a
|
||||
<classname>JdbcTemplate</classname>. It can also have a
|
||||
<classname>SqlParameterSourceFactory</classname> injected to control
|
||||
the binding of each incoming message to a query.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
If the input channel is a direct channel, then the outbound adapter runs
|
||||
its query in the same thread, and therefore the same transaction (if
|
||||
there is one) as the sender of the message.
|
||||
</para>
|
||||
|
||||
<para><emphasis>Passing Parameters using SpEL Expressions</emphasis></para>
|
||||
|
||||
<para>
|
||||
A common requirement for most JDBC Channel Adapters is to pass parameters
|
||||
as part of Sql queries or Stored Procedures/Functions. As mentioned above,
|
||||
these parameters are by default bean property expressions, not SpEL expressions.
|
||||
|
||||
However, if you need to pass SpEL expression as parameters, you must inject
|
||||
a <interfacename>SqlParameterSourceFactory</interfacename> explicitly.
|
||||
</para>
|
||||
<para>
|
||||
The following example uses a <classname>ExpressionEvaluatingSqlParameterSourceFactory</classname>
|
||||
to achieve that requirement.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<jdbc:outbound-channel-adapter data-source="dataSource" channel="input"
|
||||
query="insert into MESSAGES (MESSAGE_ID,PAYLOAD,CREATED_DATE) \
|
||||
values (:id, :payload, :createdDate)"
|
||||
sql-parameter-source-factory="spelSource"/>
|
||||
|
||||
<bean id="spelSource"
|
||||
class="o.s.integration.jdbc.ExpressionEvaluatingSqlParameterSourceFactory">
|
||||
<property name="parameterExpressions">
|
||||
<map>
|
||||
<entry key="id" value="headers['id'].toString()"/>
|
||||
<entry key="createdDate" value="new java.util.Date()"/>
|
||||
<entry key="payload" value="payload"/>
|
||||
</map>
|
||||
</property>
|
||||
</bean>]]></programlisting>
|
||||
<para>
|
||||
For further information, please also see
|
||||
<xref linkend="sp-defining-parameter-sources"/>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="jdbc-outbound-gateway">
|
||||
<title>Outbound Gateway</title>
|
||||
|
||||
<para>The outbound Gateway is like a combination of the outbound and
|
||||
inbound adapters: its role is to handle a message and use it to execute a
|
||||
SQL query and then respond with the result sending it to a reply channel.
|
||||
The message payload and headers are available by default as input
|
||||
parameters to the query, for instance:
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:outbound-gateway
|
||||
update="insert into foos (id, status, name) values (:headers[id], 0, :payload[foo])"
|
||||
request-channel="input" reply-channel="output" data-source="dataSource" />]]></programlisting></para>
|
||||
|
||||
<para>The result of the above would be to insert a record into the "foos"
|
||||
table and return a message to the output channel indicating the number of
|
||||
rows affected (the payload is a map: <literal>{UPDATED=1}</literal>).</para>
|
||||
|
||||
<para>If the update query is an insert with auto-generated keys, the reply
|
||||
message can be populated with the generated keys by adding
|
||||
<literal>keys-generated="true"</literal> to the above example (this is not
|
||||
the default because it is not supported by some database platforms). For
|
||||
example:</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:outbound-gateway
|
||||
update="insert into foos (status, name) values (0, :payload[foo])"
|
||||
request-channel="input" reply-channel="output" data-source="dataSource"
|
||||
keys-generated="true"/>]]></programlisting>
|
||||
|
||||
<para>Instead of the update count or the generated keys, you can also
|
||||
provide a select query to execute and generate a reply message from the result
|
||||
(like the inbound adapter), e.g:</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:outbound-gateway
|
||||
update="insert into foos (id, status, name) values (:headers[id], 0, :payload[foo])"
|
||||
query="select * from foos where id=:headers[$id]"
|
||||
request-channel="input" reply-channel="output" data-source="dataSource"/>]]></programlisting>
|
||||
|
||||
<para>As with the channel adapters, there is also the option to provide
|
||||
<classname>SqlParameterSourceFactory</classname> instances for request and
|
||||
reply. The default is the same as for the outbound adapter, so the request
|
||||
message is available as the root of an expression. If
|
||||
keys-generated="true" then the root of the expression is the generated
|
||||
keys (a map if there is only one or a list of maps if
|
||||
multi-valued).</para>
|
||||
|
||||
<para>The outbound gateway requires a reference to either a DataSource or
|
||||
a JdbcTemplate. It can also have a
|
||||
<classname>SqlParameterSourceFactory</classname> injected to control the
|
||||
binding of the incoming message to the query.</para>
|
||||
</section>
|
||||
|
||||
<section id="jdbc-message-store">
|
||||
<title>JDBC Message Store</title>
|
||||
|
||||
<para>The JDBC module provides an implementation of the Spring Integration
|
||||
<classname>MessageStore</classname> (important in the Claim Check pattern)
|
||||
and <classname>MessageGroupStore</classname> (important in stateful
|
||||
patterns like Aggregator) backed by a database. Both interfaces are
|
||||
implemented by the JdbcMessageStore, and there is also support for
|
||||
configuring store instances in XML. For example:</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:message-store id="messageStore" data-source="dataSource"/>
|
||||
]]></programlisting>
|
||||
|
||||
<para>A <classname>JdbcTemplate</classname> can be specified instead of a
|
||||
<classname>DataSource</classname>.</para>
|
||||
|
||||
<para>Other optional attributes are show in the next example:</para>
|
||||
|
||||
<para><programlisting language="xml"><![CDATA[<int-jdbc:message-store id="messageStore" data-source="dataSource"
|
||||
lob-handler="lobHandler" table-prefix="MY_INT_"/>]]></programlisting>
|
||||
|
||||
Here we have specified a <classname>LobHandler</classname> for dealing with
|
||||
messages as large objects (e.g. often necessary if using Oracle) and a
|
||||
prefix for the table names in the queries generated by the store. The
|
||||
table name prefix defaults to "INT_".</para>
|
||||
|
||||
<section>
|
||||
<title>Initializing the Database</title>
|
||||
|
||||
<para>Spring Integration ships with some sample scripts that can be used
|
||||
to initialize a database. In the spring-integration-jdbc JAR file you
|
||||
will find scripts in the
|
||||
<classname>org.springframework.integration.jdbc</classname> package:
|
||||
there is a create and a drop script example for a range of common
|
||||
database platforms. A common way to use these scripts is to reference
|
||||
them in a <ulink
|
||||
url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html#d0e24182">Spring
|
||||
JDBC data source initializer</ulink>. Note that the scripts are provided
|
||||
as samples or specifications of the the required table and column names.
|
||||
You may find that you need to enhance them for production use (e.g. with
|
||||
index declarations).</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Partitioning a Message Store</title>
|
||||
|
||||
<para>It is common to use a <classname>JdbcMessageStore</classname> as a
|
||||
global store for a group of applications, or nodes in the same
|
||||
application. To provide some protection against name clashes, and to
|
||||
give control over the database meta-data configuration, the message
|
||||
store allows the tables to be partitioned in two ways. One is to use
|
||||
separate table names, by changing the prefix as described above, and the
|
||||
other is to specify a "region" name for partitioning data within a
|
||||
single table. An important use case for this is when the MessageStore is
|
||||
managing persistent queues backing a Spring Integration Message Channel. The
|
||||
message data for a persistent channel is keyed in the store on the
|
||||
channel name, so if the channel names are not globally unique then there
|
||||
is the danger of channels picking up data that was not intended for
|
||||
them. To avoid this, the message store region can be used to keep data
|
||||
separate for different physical channels that happen to have the same
|
||||
logical name.</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="stored-procedures">
|
||||
<title>Stored Procedures</title>
|
||||
<para>
|
||||
In certain situations plain JDBC support is not sufficient. Maybe you
|
||||
deal with legacy relational database schemas or you have
|
||||
complex data processing needs, but ultimately you have to use
|
||||
<ulink url="http://en.wikipedia.org/wiki/Stored_procedure">Stored Procedures</ulink>
|
||||
or Stored Functions. Since Spring Integration 2.1, we provide
|
||||
three components in order to execute Stored Procedures or
|
||||
Stored Functions:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>Stored Procedures Inbound Channel Adapter</listitem>
|
||||
<listitem>Stored Procedures Outbound Channel Adapter</listitem>
|
||||
<listitem>Stored Procedures Outbound Gateway</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<section id="sp-supported-databases">
|
||||
<title>Supported Databases</title>
|
||||
<para>
|
||||
In order to enable calls to <emphasis>Stored Procedures</emphasis>
|
||||
and <emphasis>Stored Functions</emphasis>, the Stored Procedure
|
||||
components use the <ulink
|
||||
url="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html"><classname>org.springframework.jdbc.core.simple.SimpleJdbcCall</classname></ulink>
|
||||
class. Consequently, the following databases are fully supported
|
||||
for executing Stored Procedures:</para>
|
||||
<itemizedlist>
|
||||
<listitem>Apache Derby</listitem>
|
||||
<listitem>DB2</listitem>
|
||||
<listitem>MySQL</listitem>
|
||||
<listitem>Microsoft SQL Server</listitem>
|
||||
<listitem>Oracle</listitem>
|
||||
<listitem>PostgreSQL</listitem>
|
||||
<listitem>Sybase</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
If you want to exute Stored Functions instead, the following
|
||||
databases are fully supported:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>MySQL</listitem>
|
||||
<listitem>Microsoft SQL Server</listitem>
|
||||
<listitem>Oracle</listitem>
|
||||
<listitem>PostgreSQL</listitem>
|
||||
</itemizedlist>
|
||||
</section>
|
||||
<note>
|
||||
<para>
|
||||
Even though your particular database may not be fully supported,
|
||||
chances are, that you can use the Stored Procedure Spring Integration
|
||||
components quite successfully anyway, provided your RDBMS supports
|
||||
Stored Procedures or Functions.</para>
|
||||
<para>
|
||||
As a matter of fact, some of the provided integration tests use
|
||||
the <ulink url="http://www.h2database.com/">H2 database</ulink>.
|
||||
Nevertheless, it is very important to thoroughly test those usage scenarios.
|
||||
</para>
|
||||
</note>
|
||||
<section id="sp-configuration">
|
||||
<title>Configuration</title>
|
||||
<para>
|
||||
The Stored Procedure components provide full XML Namespace support
|
||||
and configuring the components is similar as for the general purpose
|
||||
JDBC components discussed earlier.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="sp-common-config-params">
|
||||
<title>Common Configuration Attributes</title>
|
||||
<para>
|
||||
Certain configuration parameters are shared among all Stored Procedure
|
||||
components and are described below:
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">auto-startup</emphasis></para>
|
||||
<para>
|
||||
Lifecycle attribute signaling if this component should
|
||||
be started during Application Context startup.
|
||||
Defaults to <code>true</code>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">data-source</emphasis></para>
|
||||
<para>
|
||||
Reference to a <interfacename>javax.sql.DataSource</interfacename>,
|
||||
which is used to access the database.
|
||||
<emphasis>Required</emphasis>.
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">id</emphasis></para>
|
||||
<para>
|
||||
Identifies the underlying Spring bean definition, which
|
||||
is an instance of either <classname>EventDrivenConsumer</classname>
|
||||
or <classname>PollingConsumer</classname>, depending
|
||||
on whether the Outbound Channel Adapter's <code>channel</code>
|
||||
attribute references a <interfacename>SubscribableChannel</interfacename>
|
||||
or a <interfacename>PollableChannel</interfacename>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">ignore-column-meta-data</emphasis></para>
|
||||
<para>
|
||||
For fully supported databases, the underlying
|
||||
<ulink url="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html"><classname>SimpleJdbcCall</classname></ulink>
|
||||
class can automatically retrieve the parameter information
|
||||
for the to be invoked Stored Procedure or Function
|
||||
from the JDBC Meta-data.
|
||||
</para>
|
||||
<para>
|
||||
However, if the used database does not support meta
|
||||
data lookups or if you like to provide customized parameter
|
||||
definitions, this flag can be set to <code>true</code>. It defaults
|
||||
to <code>false</code>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">is-function</emphasis></para>
|
||||
<para>
|
||||
If <code>true</code>, a SQL Function is called. In that case the
|
||||
<code>stored-procedure-name</code> attribute defines the name of
|
||||
the called function. Defaults to <code>false</code>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
<para><emphasis role="bold">stored-procedure-name</emphasis></para>
|
||||
<para>
|
||||
The attribute specifies the name of the stored procedure. If the
|
||||
<code>is-function</code> attribute is set to <code>true</code>,
|
||||
this attribute specifies the function name.
|
||||
<emphasis>Required</emphasis>.
|
||||
</para>
|
||||
<para><emphasis role="bold">sql-parameter-source-factory</emphasis>
|
||||
(Not available for the Stored Procedure Inbound Channel Adapter.)</para>
|
||||
|
||||
<para>
|
||||
Reference to a <interfacename>SqlParameterSourceFactory</interfacename>.
|
||||
|
||||
By default bean properties of the passed in
|
||||
<interfacename>Message</interfacename> payload will be used
|
||||
as a source for the Stored Procedure's input parameters
|
||||
using a <classname>BeanPropertySqlParameterSourceFactory</classname>.
|
||||
</para>
|
||||
<para>
|
||||
This may be sufficient for basic use cases. For more
|
||||
sophisticated options, consider passing in one or more
|
||||
<classname>ProcedureParameter</classname>. Please also refer to
|
||||
<xref linkend="sp-defining-parameter-sources"/>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">use-payload-as-parameter-source</emphasis>
|
||||
(Not available for the Stored Procedure Inbound Channel Adapter.)</para>
|
||||
|
||||
<para>
|
||||
If set to <code>true</code>, the payload of the Message
|
||||
will be used as a source for providing parameters.
|
||||
If false, however, the entire Message will be available as a
|
||||
source for parameters.
|
||||
</para>
|
||||
<para>
|
||||
If no Procedure Parameters are passed in, this property
|
||||
will default to <code>true</code>. This means that using a default
|
||||
<classname>BeanPropertySqlParameterSourceFactory</classname>
|
||||
the bean properties of the payload will be used as a
|
||||
source for parameter values for the to-be-executed
|
||||
Stored Procedure or Stored Function.
|
||||
</para>
|
||||
<para>
|
||||
However, if Procedure Parameters are passed in, then
|
||||
this property will by default evaluate to <code>false</code>.
|
||||
<classname>ProcedureParameter</classname> allow for
|
||||
SpEL Expressions to be provided and therefore it is
|
||||
highly beneficial to have access to the entire Message. The property
|
||||
is set on the underlying <classname>StoredProcExecutor</classname>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="sp-common-config-subelements">
|
||||
<title>Common Configuration Sub-Elements</title>
|
||||
<para>
|
||||
The Stored Procedure components share a common set of sub-elements
|
||||
to define and pass parameters to Stored Procedures or Functions.
|
||||
The following elements are available:
|
||||
</para>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>parameter</listitem>
|
||||
<listitem>returning-resultset</listitem>
|
||||
<listitem>sql-parameter-definition</listitem>
|
||||
<listitem>poller</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<para><emphasis role="bold">parameter</emphasis></para>
|
||||
<para>
|
||||
Provides a mechanism to provide Stored Procedure parameters.
|
||||
Parameters can be either static or provided using a SpEL Expressions.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:parameter name="" ]]><co id="sp-parameter-sub-xml01-co" linkends="sp-parameter-sub-xml01" /><![CDATA[
|
||||
type="" ]]><co id="sp-parameter-sub-xml02-co" linkends="sp-parameter-sub-xml02" /><![CDATA[
|
||||
value=""/> ]]><co id="sp-parameter-sub-xml03-co" linkends="sp-parameter-sub-xml03" /><![CDATA[
|
||||
|
||||
<int-jdbc:parameter name=""
|
||||
expression=""/>]]><co id="sp-parameter-sub-xml04-co" linkends="sp-parameter-sub-xml04" /></programlisting>
|
||||
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="sp-parameter-sub-xml01-co" id="sp-parameter-sub-xml01">
|
||||
<para>
|
||||
The name of the parameter to be passed into the
|
||||
Stored Procedure or Stored Function.
|
||||
<emphasis>Required</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-parameter-sub-xml02-co" id="sp-parameter-sub-xml02">
|
||||
<para>
|
||||
This attribute specifies the type of the value. If
|
||||
nothing is provided this attribute will default to
|
||||
<classname>java.lang.String</classname>. This attribute
|
||||
is only used when the <code>value</code> attribute is
|
||||
used.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-parameter-sub-xml03-co" id="sp-parameter-sub-xml03">
|
||||
<para>
|
||||
The value of the parameter. You have to provider either
|
||||
this attribute or the <code>expression</code> attribute must be
|
||||
provided instead.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-parameter-sub-xml04-co" id="sp-parameter-sub-xml04">
|
||||
<para>
|
||||
Instead of the <code>value</code> attribute, you can
|
||||
also specify a SpEL expression for passing the value
|
||||
of the parameter. If you specify the <code>expression</code>
|
||||
the <code>value</code> attribute is not allowed.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">returning-resultset</emphasis></para>
|
||||
<para>
|
||||
Stored Procedures may return multiple resultsets. By setting one
|
||||
or more <code>returning-resultset</code> elements, you can specify
|
||||
<interfacename>RowMappers</interfacename> in order to convert
|
||||
each returned <classname>ResultSet</classname> to meaningful objects.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:returning-resultset name="" row-mapper="" />]]></programlisting>
|
||||
|
||||
<para><emphasis role="bold">sql-parameter-definition</emphasis></para>
|
||||
|
||||
<para>
|
||||
If you are using a database that is fully supported, you typically
|
||||
don't have to specify the Stored Procedure parameter definitions.
|
||||
Instead, those parameters can be automatically derived from the
|
||||
JDBC Meta-data. However, if you are using databases that are not
|
||||
fully supported, you must set those parameters explicitly using the
|
||||
<code>sql-parameter-definition</code> sub-element.
|
||||
</para>
|
||||
<para>
|
||||
You can also choose to turn off any processing of parameter meta
|
||||
data information obtained via JDBC using the <code>ignore-column-meta-data</code>
|
||||
attribute.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:sql-parameter-definition name="" ]]><co id="sp-parameter-definition-xml01-co" linkends="sp-parameter-definition-xml01" /><![CDATA[
|
||||
direction="IN" ]]><co id="sp-parameter-definition-xml02-co" linkends="sp-parameter-definition-xml02" /><![CDATA[
|
||||
type="STRING" ]]><co id="sp-parameter-definition-xml03-co" linkends="sp-parameter-definition-xml03" /><![CDATA[
|
||||
scale=""/> ]]><co id="sp-parameter-definition-xml04-co" linkends="sp-parameter-definition-xml04" /></programlisting>
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="sp-parameter-definition-xml01-co" id="sp-parameter-definition-xml01">
|
||||
<para>
|
||||
Specifies the name of the SQL parameter.
|
||||
<emphasis>Required</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-parameter-definition-xml02-co" id="sp-parameter-definition-xml02">
|
||||
<para>
|
||||
Specifies the direction of the SQL parameter definition.
|
||||
Defaults to <code>IN</code>. Valid values are:
|
||||
<code>IN</code>,
|
||||
<code>OUT</code> and
|
||||
<code>INOUT</code>.
|
||||
If your procedure is returning ResultSets,
|
||||
please use the <code>returning-resultset</code> element.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-parameter-definition-xml03-co" id="sp-parameter-definition-xml03">
|
||||
<para>
|
||||
The SQL type used for this SQL parameter definition. Will translate
|
||||
into the integer value as defined by java.sql.Types. Alternatively
|
||||
you can provide the integer value as well. If this attribute is
|
||||
not explicitly set, then it will default to 'VARCHAR'.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-parameter-definition-xml04-co" id="sp-parameter-definition-xml04">
|
||||
<para>
|
||||
The scale of the SQL parameter. Only used for numeric and decimal
|
||||
parameters.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
|
||||
<para><emphasis role="bold">poller</emphasis></para>
|
||||
<para>
|
||||
Allows you to configure a Message Poller if this endpoint is a
|
||||
<classname>PollingConsumer</classname>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="sp-defining-parameter-sources">
|
||||
<title>Defining Parameter Sources</title>
|
||||
<para>
|
||||
Parameter Sources govern the techniques of retrieving and mapping the
|
||||
Spring Integration Message properties to the relevant Stored Procedure
|
||||
input parameters. The Stored Procedure components follow certain rules.
|
||||
</para>
|
||||
<para>
|
||||
By default bean properties of the passed in
|
||||
<interfacename>Message</interfacename> payload will be used as a
|
||||
source for the Stored Procedure's input parameters. In that case a
|
||||
<classname>BeanPropertySqlParameterSourceFactory</classname> will
|
||||
be used. This may be sufficient for basic use cases. The following
|
||||
example illustrates that default behavior.
|
||||
</para>
|
||||
<important>
|
||||
Please be aware that for the "automatic" lookup of bean properties
|
||||
using the <classname>BeanPropertySqlParameterSourceFactory</classname>
|
||||
to work, your bean properties must be defined in lower case.
|
||||
This is due to the fact that in
|
||||
<classname>org.springframework.jdbc.core.metadata.CallMetaDataContext</classname>
|
||||
(method matchInParameterValuesWithCallParameters()), the retrieved
|
||||
Stored Procedure parameter declarations are converted to lower case.
|
||||
|
||||
As a result, if you have camel-case bean properties such as "lastName",
|
||||
the lookup will fail. In that case, please provide an explicit
|
||||
<classname>ProcedureParameter</classname>.
|
||||
</important>
|
||||
<para>
|
||||
Let's assume we have a payload that consists of a simple bean with
|
||||
the following three properties: <emphasis>id</emphasis>,
|
||||
<emphasis>name</emphasis> and <emphasis>description</emphasis>.
|
||||
Furthermore, we have a simplistic Stored Procedure called <emphasis>INSERT_COFFEE</emphasis>
|
||||
that accepts three input parameters:
|
||||
<emphasis>id</emphasis>,
|
||||
<emphasis>name</emphasis> and
|
||||
<emphasis>description</emphasis>. We also use a fully supported
|
||||
database. In that case the following configuration for a Stored
|
||||
Procedure Oubound Adapter will be sufficient:
|
||||
</para>
|
||||
<programlisting><![CDATA[<int-jdbc:stored-proc-outbound-channel-adapter data-source="dataSource"
|
||||
channel="insertCoffeeProcedureRequestChannel"
|
||||
stored-procedure-name="INSERT_COFFEE"/>]]></programlisting>
|
||||
<para>
|
||||
For more sophisticated options consider passing in one or more
|
||||
<classname>ProcedureParameter</classname>.
|
||||
</para>
|
||||
<para>
|
||||
If you do provide <classname>ProcedureParameter</classname> explicitly,
|
||||
then as default an <classname>ExpressionEvaluatingSqlParameterSourceFactory</classname>
|
||||
will be used for parameter processing in order to enable the full
|
||||
power of SpEL expressions.
|
||||
</para>
|
||||
<para>
|
||||
Furthermore, if you need even more control over how parameters are
|
||||
retrieved, consider passing in a custom implementation of a
|
||||
<interfacename>SqlParameterSourceFactory</interfacename> using the
|
||||
<code>sql-parameter-source-factory</code> attribute.
|
||||
</para>
|
||||
</section>
|
||||
<section id="stored-procedure-inbound-channel-adapter">
|
||||
<title>Stored Procedure Inbound Channel Adapter</title>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:stored-proc-inbound-channel-adapter
|
||||
channel="" ]]><co id="sp-inbound-xml01-co" linkends="sp-inbound-xml01" /><![CDATA[
|
||||
stored-procedure-name=""
|
||||
data-source=""
|
||||
auto-startup="true"
|
||||
id=""
|
||||
ignore-column-meta-data="false"
|
||||
is-function="false"
|
||||
max-rows-per-poll="" ]]><co id="sp-inbound-xml02-co" linkends="sp-inbound-xml02" /><![CDATA[
|
||||
skip-undeclared-results="" ]]><co id="sp-inbound-xml03-co" linkends="sp-inbound-xml03" /><![CDATA[
|
||||
<int:poller/>
|
||||
<int-jdbc:sql-parameter-definition name="" direction="IN"
|
||||
type="STRING"
|
||||
scale=""/>
|
||||
<int-jdbc:parameter name="" type="" value=""/>
|
||||
<int-jdbc:parameter name="" expression=""/>
|
||||
<int-jdbc:returning-resultset name="" row-mapper="" />
|
||||
</int-jdbc:stored-proc-inbound-channel-adapter>]]></programlisting>
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="sp-inbound-xml01-co" id="sp-inbound-xml01">
|
||||
<para>
|
||||
Channel to which polled messages will be sent. If the stored
|
||||
procedure or function does not return any data, the payload
|
||||
of the Message will be Null.
|
||||
<emphasis>Required</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-inbound-xml02-co" id="sp-inbound-xml02">
|
||||
<para>
|
||||
Limits the number of rows extracted per query. Otherwise
|
||||
all rows are extracted into the outgoing message.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-inbound-xml03-co" id="sp-inbound-xml03">
|
||||
<para>
|
||||
If this attribute is set to <code>true</code>, then
|
||||
all results from a stored procedure call that don't
|
||||
have a corresponding <classname>SqlOutParameter</classname>
|
||||
declaration will be bypassed.
|
||||
</para>
|
||||
<para>
|
||||
E.g. Stored Procedures may return an update count value,
|
||||
even though your Stored Procedure only declared a single
|
||||
result parameter. The exact behavior depends on the used
|
||||
database. The value is set on the underlying
|
||||
<classname>JdbcTemplate</classname>.
|
||||
</para>
|
||||
<para>
|
||||
Few developers will probably ever want to process
|
||||
update counts, thus the value defaults to <code>true</code>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
</calloutlist></para>
|
||||
</section>
|
||||
<section id="stored-procedure-outbound-channel-adapter">
|
||||
<title>Stored Procedure Outbound Channel Adapter</title>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:stored-proc-outbound-channel-adapter channel="" ]]><co id="sp-outbound-xml01-co" linkends="sp-outbound-xml01" /><![CDATA[
|
||||
stored-procedure-name=""
|
||||
data-source=""
|
||||
auto-startup="true"
|
||||
id=""
|
||||
ignore-column-meta-data="false"
|
||||
order="" ]]><co id="sp-outbound-xml02-co" linkends="sp-outbound-xml02" /><![CDATA[
|
||||
return-value-required="false" ]]><co id="sp-outbound-xml03-co" linkends="sp-outbound-xml03" /><![CDATA[
|
||||
sql-parameter-source-factory=""
|
||||
use-payload-as-parameter-source="">
|
||||
<int:poller fixed-rate=""/>
|
||||
<int-jdbc:sql-parameter-definition name=""/>
|
||||
<int-jdbc:parameter name=""/>
|
||||
|
||||
</int-jdbc:stored-proc-outbound-channel-adapter>]]></programlisting>
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="sp-outbound-xml01-co" id="sp-outbound-xml01">
|
||||
<para>
|
||||
The receiving Message Channel of this endpoint.
|
||||
<emphasis>Required</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-outbound-xml02-co" id="sp-outbound-xml02">
|
||||
<para>
|
||||
Specifies the order for invocation when this endpoint
|
||||
is connected as a subscriber to a channel. This is
|
||||
particularly relevant when that channel is using a
|
||||
<emphasis>failover</emphasis> dispatching strategy.
|
||||
It has no effect when this endpoint itself is a
|
||||
Polling Consumer for a channel with a queue.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-outbound-xml03-co" id="sp-outbound-xml03">
|
||||
<para>
|
||||
Indicates whether this procedure's return value
|
||||
should be included.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
</calloutlist></para>
|
||||
</section>
|
||||
<section id="stored-procedure-outbound-gateway">
|
||||
<title>Stored Procedure Outbound Gateway</title>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:stored-proc-outbound-gateway request-channel="" ]]><co id="sp-gateway-xml01-co" linkends="sp-gateway-xml01" /><![CDATA[
|
||||
stored-procedure-name=""
|
||||
data-source=""
|
||||
auto-startup="true"
|
||||
id=""
|
||||
ignore-column-meta-data="false"
|
||||
is-function="false"
|
||||
order=""
|
||||
reply-channel="" ]]><co id="sp-gateway-xml02-co" linkends="sp-gateway-xml02" /><![CDATA[
|
||||
reply-timeout="" ]]><co id="sp-gateway-xml03-co" linkends="sp-gateway-xml03" /><![CDATA[
|
||||
return-value-required="false" ]]><co id="sp-gateway-xml04-co" linkends="sp-gateway-xml04" /><![CDATA[
|
||||
skip-undeclared-results="" ]]><co id="sp-gateway-xml05-co" linkends="sp-gateway-xml05" /><![CDATA[
|
||||
sql-parameter-source-factory=""
|
||||
use-payload-as-parameter-source="">
|
||||
<int-jdbc:sql-parameter-definition name="" direction="IN"
|
||||
type=""
|
||||
scale="10"/>
|
||||
<int-jdbc:sql-parameter-definition name=""/>
|
||||
<int-jdbc:parameter name="" type="" value=""/>
|
||||
<int-jdbc:parameter name="" expression=""/>
|
||||
<int-jdbc:returning-resultset name="" row-mapper="" />]]></programlisting>
|
||||
|
||||
<para>
|
||||
<calloutlist>
|
||||
<callout arearefs="sp-gateway-xml01-co" id="sp-gateway-xml01">
|
||||
<para>
|
||||
The receiving Message Channel of this endpoint.
|
||||
<emphasis>Required</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-gateway-xml02-co" id="sp-gateway-xml02">
|
||||
<para>
|
||||
Message Channel to which replies should be sent,
|
||||
after receiving the database response.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-gateway-xml03-co" id="sp-gateway-xml03">
|
||||
<para>
|
||||
Allows you to specify how long this gateway will wait
|
||||
for the reply message to be sent successfully before
|
||||
throwing an exception. Keep in mind that when sending
|
||||
to a <classname>DirectChannel</classname>, the invocation
|
||||
will occur in the sender's thread so the failing of the
|
||||
send operation may be caused by other components further
|
||||
downstream.
|
||||
|
||||
By default the Gateway will wait indefinitely. The
|
||||
value is specified in milliseconds.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-gateway-xml04-co" id="sp-gateway-xml04">
|
||||
<para>
|
||||
Indicates whether this procedure's return value
|
||||
should be included.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
<callout arearefs="sp-gateway-xml05-co" id="sp-gateway-xml05">
|
||||
<para>
|
||||
If the <code>skip-undeclared-results</code> attribute
|
||||
is set to <code>true</code>, then all results from
|
||||
a stored procedure call that don't have a
|
||||
corresponding <classname>SqlOutParameter</classname>
|
||||
declaration will be bypassed.
|
||||
</para>
|
||||
<para>
|
||||
E.g. Stored Procedures may return an update count value,
|
||||
even though your Stored Procedure only declared a single
|
||||
result parameter. The exact behavior depends on the used
|
||||
database. The value is set on the underlying
|
||||
<classname>JdbcTemplate</classname>.
|
||||
</para>
|
||||
<para>
|
||||
Few developers will probably ever want to process
|
||||
update counts, thus the value defaults to <code>true</code>.
|
||||
<emphasis>Optional</emphasis>.
|
||||
</para>
|
||||
</callout>
|
||||
</calloutlist>
|
||||
</para>
|
||||
</section>
|
||||
<section id="sp-examples">
|
||||
<title>Examples</title>
|
||||
<para>
|
||||
In the following two examples we call <ulink url="http://db.apache.org/derby/">Apache Derby</ulink>
|
||||
Stored Procedures. The first procedure will call a Stored Procedure that
|
||||
returns a <classname>ResultSet</classname>, and using a <interfacename>RowMapper</interfacename>
|
||||
the data is converted into a domain object, which then becomes the
|
||||
Spring Integration message payload.
|
||||
</para>
|
||||
<para>
|
||||
In the second sample we call a Stored Procedure that uses
|
||||
Output Parameters instead, in order to return data.
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
Please have a look at the <emphasis>Spring Integration Samples</emphasis>
|
||||
project, located at
|
||||
<ulink url="https://github.com/SpringSource/spring-integration-samples"/>
|
||||
</para>
|
||||
<para>
|
||||
The project contains the Apache Derby example referenced
|
||||
here, as well as instruction on how to run it. The
|
||||
<emphasis>Spring Integration Samples</emphasis> project also
|
||||
provides an
|
||||
<ulink url="https://github.com/SpringSource/spring-integration-samples/tree/master/intermediate/stored-procedures-oracle">example</ulink>
|
||||
using Oracle Stored Procedures.
|
||||
</para>
|
||||
</note>
|
||||
<para>
|
||||
In the first example, we call a Stored Procedure named
|
||||
<emphasis>FIND_ALL_COFFEE_BEVERAGES</emphasis> that does not
|
||||
define any input parameters but which returns a <classname>ResultSet</classname>.
|
||||
</para>
|
||||
<para>
|
||||
In Apache Derby, Stored Procedures are implemented using Java. Here
|
||||
is the method signature followed by the corresponding Sql:
|
||||
</para>
|
||||
<programlisting language="java"><![CDATA[public static void findAllCoffeeBeverages(ResultSet[] coffeeBeverages)
|
||||
throws SQLException {
|
||||
...
|
||||
}]]></programlisting>
|
||||
|
||||
<programlisting language="xml"><![CDATA[CREATE PROCEDURE FIND_ALL_COFFEE_BEVERAGES() \
|
||||
PARAMETER STYLE JAVA LANGUAGE JAVA MODIFIES SQL DATA DYNAMIC RESULT SETS 1 \
|
||||
EXTERNAL NAME 'org.springframework.integration.jdbc.storedproc.derby.DerbyStoredProcedures.findAllCoffeeBeverages';
|
||||
]]></programlisting>
|
||||
|
||||
<para>
|
||||
In Spring Integration, you can now call this Stored Procedure using
|
||||
e.g. a <code>stored-proc-outbound-gateway</code>
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:stored-proc-outbound-gateway id="outbound-gateway-storedproc-find-all"
|
||||
data-source="dataSource"
|
||||
request-channel="findAllProcedureRequestChannel"
|
||||
expect-single-result="true"
|
||||
stored-procedure-name="FIND_ALL_COFFEE_BEVERAGES">
|
||||
<int-jdbc:returning-resultset name="coffeeBeverages"
|
||||
row-mapper="org.springframework.integration.support.CoffeBeverageMapper"/>
|
||||
</int-jdbc:stored-proc-outbound-gateway>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the second example, we call a Stored Procedure named
|
||||
<emphasis>FIND_COFFEE</emphasis> that has one input parameter. Instead
|
||||
of returning a ResultSet, an output parameter is used:
|
||||
</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[public static void findCoffee(int coffeeId, String[] coffeeDescription)
|
||||
throws SQLException {
|
||||
...
|
||||
}]]></programlisting>
|
||||
|
||||
<programlisting><![CDATA[CREATE PROCEDURE FIND_COFFEE(IN ID INTEGER, OUT COFFEE_DESCRIPTION VARCHAR(200)) \
|
||||
PARAMETER STYLE JAVA LANGUAGE JAVA EXTERNAL NAME \
|
||||
'org.springframework.integration.jdbc.storedproc.derby.DerbyStoredProcedures.findCoffee';]]></programlisting>
|
||||
|
||||
<para>
|
||||
In Spring Integration, you can now call this Stored Procedure using
|
||||
e.g. a <code>stored-proc-outbound-gateway</code>
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int-jdbc:stored-proc-outbound-gateway id="outbound-gateway-storedproc-find-coffee"
|
||||
data-source="dataSource"
|
||||
request-channel="findCoffeeProcedureRequestChannel"
|
||||
skip-undeclared-results="true"
|
||||
stored-procedure-name="FIND_COFFEE"
|
||||
expect-single-result="true">
|
||||
<int-jdbc:parameter name="ID" expression="payload" />
|
||||
</int-jdbc:stored-proc-outbound-gateway>]]></programlisting>
|
||||
|
||||
</section>
|
||||
</section>
|
||||
</chapter>
|
||||
344
src/reference/docbook/jms.xml
Normal file
@@ -0,0 +1,344 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="jms"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>JMS Support</title>
|
||||
<para>
|
||||
Spring Integration provides Channel Adapters for receiving and sending JMS messages. There are actually two
|
||||
JMS-based inbound Channel Adapters. The first uses Spring's <classname>JmsTemplate</classname> to receive based on
|
||||
a polling period. The second is "message-driven" and relies upon a Spring MessageListener container. There is also
|
||||
an outbound Channel Adapter which uses the <classname>JmsTemplate</classname> to convert and send a JMS Message on
|
||||
demand.
|
||||
</para>
|
||||
<para>
|
||||
As you can see from above by using <classname>JmsTemplate</classname> and <classname>MessageListener</classname> container Spring Integration relies on Spring's JMS support.
|
||||
This is important to understand since most of the attributes exposed on these adapters will configure the underlying Spring's <classname>JmsTemplate</classname> and/or
|
||||
<classname>MessageListener</classname> container. For more details about <classname>JmsTemplate</classname> and <classname>MessageListener</classname> container please refer to
|
||||
<ulink url="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jms.html">Spring JMS documentation</ulink>.
|
||||
</para>
|
||||
<para>
|
||||
Whereas the JMS Channel Adapters are intended for unidirectional Messaging (send-only or receive-only), Spring
|
||||
Integration also provides inbound and outbound JMS Gateways for request/reply operations. The inbound gateway
|
||||
relies on one of Spring's MessageListener container implementations for Message-driven reception that is also
|
||||
capable of sending a return value to the "reply-to" Destination as provided by the received Message. The outbound
|
||||
Gateway sends a JMS Message to a "request-destination" and then receives a reply Message. The "reply-destination"
|
||||
reference (or "reply-destination-name") can be configured explicitly or else the outbound gateway will use a
|
||||
JMS TemporaryQueue.
|
||||
</para>
|
||||
|
||||
<section id="jms-inbound-channel-adapter">
|
||||
<title>Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The inbound Channel Adapter requires a reference to either a single <classname>JmsTemplate</classname>
|
||||
instance or both <interfacename>ConnectionFactory</interfacename> and <interfacename>Destination</interfacename>
|
||||
(a 'destinationName' can be provided in place of the 'destination' reference). The following example defines an
|
||||
inbound Channel Adapter with a <classname>Destination</classname> reference.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:inbound-channel-adapter id="jmsIn" destination="inQueue" channel="exampleChannel">
|
||||
<int:poller fixed-rate="30000"/>
|
||||
</int-jms:inbound-channel-adapter>]]></programlisting>
|
||||
<tip>
|
||||
Notice from the configuration that the inbound-channel-adapter is a Polling Consumer. That means that
|
||||
it invokes receive() when triggered. This should only be used in situations where polling is done relatively
|
||||
infrequently and timeliness is not important. For all other situations (a vast majority of JMS-based use-cases),
|
||||
the <emphasis>message-driven-channel-adapter</emphasis> described below is a better option.
|
||||
</tip>
|
||||
<note>
|
||||
All of the JMS adapters that require a reference to the ConnectionFactory will automatically look for
|
||||
a bean named "connectionFactory" by default. That is why you don't see a "connection-factory" attribute
|
||||
in many of the examples. However, if your JMS ConnectionFactory has a different bean name, then you will
|
||||
need to provide that attribute.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
If 'extract-payload' is set to true (which is the default), the received JMS Message will be passed through
|
||||
the MessageConverter. When relying on the default SimpleMessageConverter, this means that the resulting Spring
|
||||
Integration Message will have the JMS Message's body as its payload. A JMS TextMessage will produce a
|
||||
String-based payload, a JMS BytesMessage will produce a byte array payload, and a JMS ObjectMessage's
|
||||
Serializable instance will become the Spring Integration Message's payload. If instead you prefer to have
|
||||
the raw JMS Message as the Spring Integration Message's payload, then set 'extract-payload' to false.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:inbound-channel-adapter id="jmsIn"
|
||||
destination="inQueue"
|
||||
channel="exampleChannel"
|
||||
extract-payload="false"/>
|
||||
<int:poller fixed-rate="30000"/>
|
||||
</int-jms:inbound-channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="jms-message-driven-channel-adapter">
|
||||
<title>Message-Driven Channel Adapter</title>
|
||||
<para>
|
||||
The "message-driven-channel-adapter" requires a reference to either an instance of a Spring MessageListener
|
||||
container (any subclass of <classname>AbstractMessageListenerContainer</classname>) or both
|
||||
<interfacename>ConnectionFactory</interfacename> and <interfacename>Destination</interfacename>
|
||||
(a 'destinationName' can be provided in place of the 'destination' reference). The following example defines a
|
||||
message-driven Channel Adapter with a <classname>Destination</classname> reference.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:message-driven-channel-adapter id="jmsIn" destination="inQueue" channel="exampleChannel"/>]]></programlisting>
|
||||
<note>
|
||||
The Message-Driven adapter also accepts several properties that pertain to the MessageListener container.
|
||||
These values are only considered if you do not provide an actual 'container' reference. In that case,
|
||||
an instance of DefaultMessageListenerContainer will be created and configured based on these properties.
|
||||
For example, you can specify the "transaction-manager" reference, the "concurrent-consumers" value, and
|
||||
several other property references and values. Refer to the JavaDoc and Spring Integration's JMS Schema
|
||||
(spring-integration-jms.xsd) for more detail.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
The 'extract-payload' property has the same effect as described above, and once again its default value
|
||||
is 'true'. The poller sub-element is not applicable for a message-driven
|
||||
Channel Adapter, as it will be actively invoked. For most usage scenarios, the message-driven approach is better since the Messages will
|
||||
be passed along to the <interfacename>MessageChannel</interfacename> as soon as they are received from the underlying
|
||||
JMS consumer.
|
||||
</para>
|
||||
<para>Finally, the <message-driven-channel-adapter> also accepts the 'error-channel' attribute. This
|
||||
provides the same basic functionality as described in <xref linkend="gateway-proxy"/>.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:message-driven-channel-adapter id="jmsIn" destination="inQueue"
|
||||
channel="exampleChannel"
|
||||
error-channel="exampleErrorChannel"/>
|
||||
]]></programlisting>
|
||||
When comparing this to the generic gateway configuration, or the JMS 'inbound-gateway' that will
|
||||
be discussed below, the key difference here is that we are in a one-way flow
|
||||
since this is a 'channel-adapter', not a gateway. Therefore, the flow downstream from the
|
||||
'error-channel' should also be one-way. For example, it could simply send to a logging handler,
|
||||
or it could be connected to a different JMS <outbound-channel-adapter> element.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="jms-outbound-channel-adapter">
|
||||
<title>Outbound Channel Adapter</title>
|
||||
<para>
|
||||
The <classname>JmsSendingMessageHandler</classname> implements the <interfacename>MessageHandler</interfacename>
|
||||
interface and is capable of converting Spring Integration <interfacename>Messages</interfacename> to JMS messages
|
||||
and then sending to a JMS destination. It requires either a 'jmsTemplate' reference or both 'connectionFactory' and
|
||||
'destination' references (again, the 'destinationName' may be provided in place of the 'destination'). As with the
|
||||
inbound Channel Adapter, the easiest way to configure this adapter is with the namespace support. The following
|
||||
configuration will produce an adapter that receives Spring Integration Messages from the "exampleChannel" and then
|
||||
converts those into JMS Messages and sends them to the JMS Destination reference whose bean name is "outQueue".
|
||||
<programlisting language="xml"><![CDATA[<int-jms:outbound-channel-adapter id="jmsOut" destination="outQueue" channel="exampleChannel"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
As with the inbound Channel Adapters, there is an 'extract-payload' property. However, the meaning is reversed
|
||||
for the outbound adapter. Rather than applying to the JMS Message, the boolean property applies to the Spring
|
||||
Integration Message payload. In other words, the decision is whether to pass the Spring Integration Message
|
||||
<emphasis>itself</emphasis> as the JMS Message body or whether to pass the Spring Integration Message's
|
||||
payload as the JMS Message body. The default value is once again 'true'. Therefore, if you pass a Spring
|
||||
Integration Message whose payload is a String, a JMS TextMessage will be created. If on the other hand you
|
||||
want to send the actual Spring Integration Message to another system via JMS, then simply set this to 'false'.
|
||||
<note>
|
||||
Regardless of the boolean value for payload extraction, the Spring Integration MessageHeaders will map to
|
||||
JMS properties as long as you are relying on the default converter or provide a reference to another
|
||||
instance of HeaderMappingMessageConverter (the same holds true for 'inbound' adapters except that in
|
||||
those cases, it's the JMS properties mapping <emphasis>to</emphasis> Spring Integration MessageHeaders).
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="jms-inbound-gateway">
|
||||
<title>Inbound Gateway</title>
|
||||
<para>
|
||||
Spring Integration's message-driven JMS inbound-gateway delegates to a
|
||||
<interfacename>MessageListener</interfacename> container, supports dynamically adjusting concurrent consumers,
|
||||
and can also handle replies. The inbound gateway requires references to a
|
||||
<interfacename>ConnectionFactory</interfacename>, and a request <interfacename>Destination</interfacename> (or
|
||||
'requestDestinationName'). The following example defines a JMS "inbound-gateway" that receives from the JMS
|
||||
queue referenced by the bean id "inQueue" and sends to the Spring Integration channel named "exampleChannel".
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:inbound-gateway id="jmsInGateway"
|
||||
request-destination="inQueue"
|
||||
request-channel="exampleChannel"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Since the gateways provide request/reply behavior instead of unidirectional send <emphasis>or</emphasis>
|
||||
receive, they also have two distinct properties for the "payload extraction" (as discussed above for the
|
||||
Channel Adapters' 'extract-payload' setting). For an inbound-gateway, the 'extract-request-payload' property
|
||||
determines whether the received JMS Message body will be extracted. If 'false', the JMS Message itself will
|
||||
become the Spring Integration Message payload. The default is 'true'.
|
||||
</para>
|
||||
<para>
|
||||
Similarly, for an inbound-gateway the 'extract-reply-payload' property applies to the Spring Integration Message
|
||||
that is going to be converted into a reply JMS Message. If you want to pass the whole Spring Integration Message
|
||||
(as the body of a JMS ObjectMessage) then set this to 'false'. By default, it is also 'true' such that the Spring
|
||||
Integration Message <emphasis>payload</emphasis> will be converted into a JMS Message (e.g. String payload
|
||||
becomes a JMS TextMessage).
|
||||
</para>
|
||||
<para>
|
||||
As with anything else, Gateway invocation might result in error.
|
||||
By default Producer will not be notified of the errors that might have occurred on the consumer side and will time out waiting for
|
||||
the reply. However there might be times when you want to communicate an error condition back to the consumer,
|
||||
in other words treat the Exception as a valid reply by mapping it to a Message. To accomplish this
|
||||
JMS Inbound Gateway provides support for a Message Channel to which errors
|
||||
can be sent for processing, potentially resulting in a reply Message payload
|
||||
that conforms to some contract defining what a caller may expect as an "error"
|
||||
reply. Such a channel can be configured via the <emphasis>error-channel</emphasis>
|
||||
attribute.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-jms:inbound-gateway request-destination="requestQueue"
|
||||
request-channel="jmsinputchannel"
|
||||
error-channel="errorTransformationChannel"/>
|
||||
|
||||
<int:transformer input-channel="exceptionTransformationChannel"
|
||||
ref="exceptionTransformer" method="createErrorResponse"/>
|
||||
]]></programlisting>
|
||||
You might notice that this example looks very similar to that included
|
||||
within <xref linkend="gateway-proxy"/>.
|
||||
The same idea applies here: The <emphasis>exceptionTransformer</emphasis>
|
||||
could be a simple POJO that creates error response objects, you could reference
|
||||
the "nullChannel" to suppress the errors, or you could leave 'error-channel' out
|
||||
to let the Exception propagate.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="jms-outbound-gateway">
|
||||
<title>Outbound Gateway</title>
|
||||
<para>
|
||||
The outbound Gateway creates JMS Messages from Spring Integration Messages and then sends to a
|
||||
'request-destination'. It will then handle the JMS reply Message either by using a selector to
|
||||
receive from the 'reply-destination' that you configure, or if no 'reply-destination' is provided,
|
||||
it will create JMS TemporaryQueues. Notice that the "reply-channel" is also provided.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:outbound-gateway id="jmsOutGateway"
|
||||
request-destination="outQueue"
|
||||
request-channel="outboundJmsRequests"
|
||||
reply-channel="jmsReplies"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The 'outbound-gateway' payload extraction properties are inversely related to those of the
|
||||
'inbound-gateway' (see the discussion above). That means that the 'extract-request-payload' property value
|
||||
applies to the Spring Integration Message that is being converted into a JMS Message to be
|
||||
<emphasis>sent as a request</emphasis>, and the 'extract-reply-payload' property value applies to the
|
||||
JMS Message that is <emphasis>received as a reply</emphasis> and then converted into a Spring Integration
|
||||
Message to be subsequently sent to the 'reply-channel' as shown in the example configuration above.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="jms-header-mapping">
|
||||
<title>Mapping Message Headers to/from JMS Message</title>
|
||||
|
||||
<para>
|
||||
JMS Message can contain meta-information such as JMS API headers as well as simple properties.
|
||||
You can map those to/from Spring Integration Message Headers using <classname>JmsHeaderMapper</classname>.
|
||||
The JMS API headers are passed to the appropriate setter methods (e.g. setJMSReplyTo) whereas other headers will
|
||||
be copied to the general properties of the JMS Message.
|
||||
|
||||
JMS Outbound Gateway is bootstrapped with the default implementation of <classname>JmsHeaderMapper</classname> which will map
|
||||
standard JMS API Headers as well as primitive/String Message Headers. Custom header mapper could also be
|
||||
provided via <code>header-mapper</code> attribute of inbound and outbound gateways.
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
|
||||
<section id="jms-conversion-and-marshalling">
|
||||
<title>Message Conversion, Marshalling and Unmarshalling</title>
|
||||
<para>
|
||||
If you need to convert the message, all JMS adapters and gateways, allow you to
|
||||
provide a <interfacename>MessageConverter</interfacename> via <emphasis>message-converter</emphasis> attribute. Simply provide the
|
||||
bean name of an instance of <interfacename>MessageConverter</interfacename> that is available within the same
|
||||
ApplicationContext.
|
||||
Also, to provide some consistency with Marshaller and Unmarshaller interfaces Spring provides <interfacename>MarshallingMessageConverter</interfacename>
|
||||
which you can configure with your own custom Marshallers and Unmarshallers
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:inbound-gateway request-destination="requestQueue"
|
||||
request-channel="inbound-gateway-channel"
|
||||
message-converter="marshallingMessageConverter"/>
|
||||
|
||||
<bean id="marshallingMessageConverter"
|
||||
class="org.springframework.jms.support.converter.MarshallingMessageConverter">
|
||||
<constructor-arg>
|
||||
<bean class="org.bar.SampleMarshaller"/>
|
||||
</constructor-arg>
|
||||
<constructor-arg>
|
||||
<bean class="org.bar.SampleUnmarshaller"/>
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
]]></programlisting>
|
||||
|
||||
|
||||
<note>
|
||||
Note, however, that when you provide your own MessageConverter instance, it will still
|
||||
be wrapped within the HeaderMappingMessageConverter. This means that the 'extract-request-payload'
|
||||
and 'extract-reply-payload' properties may affect what actual objects are passed to your converter. The
|
||||
HeaderMappingMessageConverter itself simply delegates to a target MessageConverter while also mapping the
|
||||
Spring Integration MessageHeaders to JMS Message properties and vice-versa.
|
||||
</note>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="jms-channel">
|
||||
<title>JMS Backed Message Channels</title>
|
||||
<para>
|
||||
The Channel Adapters and Gateways featured above are all intended for applications that are integrating
|
||||
with other external systems. The inbound options assume that some other system is sending JMS Messages
|
||||
to the JMS Destination and the outbound options assume that some other system is receiving from the
|
||||
Destination. The other system may or may not be a Spring Integration application. Of course, when sending
|
||||
the Spring Integration Message instance as the body of the JMS Message itself (with the 'extract-payload'
|
||||
value set to false), it is assumed that the other system is based on Spring Integration. However,
|
||||
that is by no means a requirement. That flexibility is one of the benefits of using a Message-based
|
||||
integration option with the abstraction of "channels" or Destinations in the case of JMS.
|
||||
</para>
|
||||
<para>
|
||||
There are cases where both the producer and consumer for a given JMS Destination are intended to be
|
||||
part of the same application, running within the same process. This could be accomplished by using a
|
||||
pair of inbound and outbound Channel Adapters. The problem with that approach is that two adapters are
|
||||
required even though conceptually the goal is to have a single Message Channel. A better option is
|
||||
supported as of Spring Integration version 2.0. Now it is possible to define a single "channel" when
|
||||
using the JMS namespace.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:channel id="jmsChannel" queue="exampleQueue"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The channel in the above example will behave much like a normal <channel/> element from the main
|
||||
Spring Integration namespace. It can be referenced by both "input-channel" and "output-channel" attributes
|
||||
of any endpoint. The difference is that this channel is backed by a JMS Queue instance named "exampleQueue".
|
||||
This means that asynchronous messaging is possible between the producing and consuming endpoints, but
|
||||
unlike the simpler asynchronous Message Channels created by adding a <queue/> sub-element within a
|
||||
non-JMS <channel/> element, the Messages are not just stored in an in-memory queue. Instead those
|
||||
Messages are passed within a JMS Message body, and the full power of the underlying JMS provider is then
|
||||
available for that channel. Probably the most common rationale for using this alternative would be to
|
||||
take advantage of the persistence made available by the <emphasis>store and forward</emphasis> approach
|
||||
of JMS messaging. If configured properly, the JMS-backed Message Channel also supports transactions.
|
||||
In other words, a producer would not actually write to a transactional JMS-backed channel if its send
|
||||
operation is part of a transaction that rolls back. Likewise, a consumer would not physically remove a
|
||||
JMS Message from the channel if the reception of that Message is part of a transaction that rolls back.
|
||||
Note that the producer and consumer transactions are separate in such a scenario. This is significantly
|
||||
different than the propagation of a transactional context across the simple, synchronous <channel/>
|
||||
element that has no <queue/> sub-element.
|
||||
</para>
|
||||
<para>
|
||||
Since the example above is referencing a JMS Queue instance, it will act as a point-to-point channel. If
|
||||
on the other hand, publish/subscribe behavior is needed, then a separate element can be used, and a JMS
|
||||
Topic can be referenced instead.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:publish-subscribe-channel id="jmsChannel" topic="exampleTopic"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
For either type of JMS-backed channel, the name of the destination may be provided instead of a reference.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:channel id="jmsQueueChannel" queue-name="exampleQueueName"/>
|
||||
|
||||
<jms:publish-subscribe-channel id="jmsTopicChannel" topic-name="exampleTopicName"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
In the examples above, the Destination names would be resolved by Spring's default
|
||||
<classname>DynamicDestinationResolver</classname> implementation, but any implementation of the
|
||||
<interfacename>DestinationResolver</interfacename> interface could be provided. Also, the JMS
|
||||
<interfacename>ConnectionFactory</interfacename> is a required property of the channel, but by default
|
||||
the expected bean name would be "connectionFactory". The example below provides both a custom instance
|
||||
for resolution of the JMS Destination names and a different name for the ConnectionFactory.
|
||||
<programlisting language="xml"><![CDATA[ <int-jms:channel id="jmsChannel" queue-name="exampleQueueName"
|
||||
destination-resolver="customDestinationResolver"
|
||||
connection-factory="customConnectionFactory"/>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="jms-samples">
|
||||
<title>JMS Samples</title>
|
||||
<para>
|
||||
To experiment with these JMS adapters, check out JMS samples available in our new Samples Git repository
|
||||
available here: http://git.springsource.org/+spring-integration/spring-integration/samples .
|
||||
There are two samples included. One provides inbound and outbound Channel Adapters, and the
|
||||
other provides inbound and outbound Gateways. They are configured to run with an embedded ActiveMQ process, but
|
||||
the "common.xml" file can easily be modified to support either a different JMS provider or a standalone
|
||||
ActiveMQ process. In other words, you can split the configuration so that the inbound and outbound adapters are
|
||||
running in separate JVMs. If you have ActiveMQ installed, simply modify the "brokerURL" property within the
|
||||
configuration to use "tcp://localhost:61616" for example (instead of "vm://localhost"). Both of the samples
|
||||
accept input via stdin and then echo back to stdout. Look at the configuration to see how these messages are
|
||||
routed over JMS.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
365
src/reference/docbook/jmx.xml
Normal file
@@ -0,0 +1,365 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section version="5.0" xml:id="jmx" xmlns="http://docbook.org/ns/docbook"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:ns5="http://www.w3.org/1999/xhtml"
|
||||
xmlns:ns4="http://www.w3.org/1998/Math/MathML"
|
||||
xmlns:ns3="http://www.w3.org/2000/svg"
|
||||
xmlns:ns="http://docbook.org/ns/docbook">
|
||||
<title id="jmx.title">JMX Support</title>
|
||||
|
||||
<para>Spring Integration provides Channel Adapters for receiving and
|
||||
publishing JMX Notifications. There is also an inbound Channel Adapter for
|
||||
polling JMX MBean attribute values, and an outbound Channel Adapter for
|
||||
invoking JMX MBean operations.</para>
|
||||
|
||||
<section id="jmx-notification-listening-channel-adapter">
|
||||
<title>Notification Listening Channel Adapter</title>
|
||||
|
||||
<para>The Notification-listening Channel Adapter requires a JMX ObjectName
|
||||
for the MBean that publishes Notifications to which this listener should
|
||||
be registered. A very simple configuration might look like this:
|
||||
<programlisting language="xml"> <int-jmx:notification-listening-channel-adapter id="adapter"
|
||||
channel="channel"
|
||||
object-name="example.domain:name=publisher"/></programlisting>
|
||||
<tip> The <emphasis>notification-listening-channel-adapter</emphasis>
|
||||
registers with an MBeanServer at startup, and the default bean name is
|
||||
"mbeanServer" which happens to be the same bean name generated when using
|
||||
Spring's <context:mbean-server/> element. If you need to use a
|
||||
different name be sure to include the "mbean-server" attribute. </tip> The
|
||||
adapter can also accept a reference to a NotificationFilter and a
|
||||
"handback" Object to provide some context that is passed back with each
|
||||
Notification. Both of those attributes are optional. Extending the above
|
||||
example to include those attributes as well as an explicit MBeanServer
|
||||
bean name would produce the following: <programlisting language="xml"> <int-jmx:notification-listening-channel-adapter id="adapter"
|
||||
channel="channel"
|
||||
mbean-server="someServer"
|
||||
object-name="example.domain:name=somePublisher"
|
||||
notification-filter="notificationFilter"
|
||||
handback="myHandback"/></programlisting> Since the
|
||||
notification-listening adapter is registered with the MBeanServer
|
||||
directly, it is event-driven and does not require any poller
|
||||
configuration.</para>
|
||||
</section>
|
||||
|
||||
<section id="jmx-notification-publishing-channel-adapter">
|
||||
<title>Notification Publishing Channel Adapter</title>
|
||||
|
||||
<para>The Notification-publishing Channel Adapter is relatively simple. It
|
||||
only requires a JMX ObjectName in its configuration as shown below.
|
||||
<programlisting language="xml"> <context:mbean:export/>
|
||||
|
||||
<int-jmx:notification-publishing-channel-adapter id="adapter"
|
||||
channel="channel"
|
||||
object-name="example.domain:name=publisher"/></programlisting>
|
||||
It does also require that an MBeanExporter be present in the context. That
|
||||
is why the <context:mbean-export/> element is shown above as
|
||||
well.</para>
|
||||
|
||||
<para>When Messages are sent to the channel for this adapter, the
|
||||
Notification is created from the Message content. If the payload is a
|
||||
String it will be passed as the "message" text for the Notification. Any
|
||||
other payload type will be passed as the "userData" of the
|
||||
Notification.</para>
|
||||
|
||||
<para>JMX Notifications also have a "type", and it should be a
|
||||
dot-delimited String. There are two ways to provide the type. Precedence
|
||||
will always be given to a Message header value associated with the
|
||||
JmxHeaders.NOTIFICATION_TYPE key. On the other hand, you can rely on a
|
||||
fallback "default-notification-type" attribute provided in the
|
||||
configuration. <programlisting language="xml"> <context:mbean:export/>
|
||||
|
||||
<int-jmx:notification-publishing-channel-adapter id="adapter"
|
||||
channel="channel"
|
||||
object-name="example.domain:name=publisher"
|
||||
default-notification-type="some.default.type"/></programlisting></para>
|
||||
</section>
|
||||
|
||||
<section id="jmx-attribute-polling-channel-adapter">
|
||||
<title>Attribute Polling Channel Adapter</title>
|
||||
|
||||
<para>The attribute polling adapter is useful when you have a requirement
|
||||
to periodically check on some value that is available through an MBean as
|
||||
a managed attribute. The poller can be configured in the same way as any
|
||||
other polling adapter in Spring Integration (or it's possible to rely on
|
||||
the default poller). The "object-name" and "attribute-name" are required.
|
||||
An MBeanServer reference is also required, but it will automatically check
|
||||
for a bean named "mbeanServer" by default just like the
|
||||
notification-listening-channel-adapter described above. <programlisting
|
||||
language="xml"> <int-jmx:attribute-polling-channel-adapter id="adapter"
|
||||
channel="channel"
|
||||
object-name="example.domain:name=someService"
|
||||
attribute-name="InvocationCount">
|
||||
<int:poller max-messages-per-poll="1" fixed-rate="5000"/>
|
||||
</int-jmx:attribute-polling-channel-adapter></programlisting></para>
|
||||
</section>
|
||||
|
||||
<section id="jmx-operation-invoking-channel-adapter">
|
||||
<title>Operation Invoking Channel Adapter</title>
|
||||
|
||||
<para>The <emphasis>operation-invoking-channel-adapter</emphasis> enables
|
||||
Message-driven invocation of any managed operation exposed by an MBean.
|
||||
Each invocation requires the operation name to be invoked and the
|
||||
ObjectName of the target MBean. Both of these must be explicitly provided
|
||||
via adapter configuration: <programlisting language="xml"> <int-jmx:operation-invoking-channel-adapter id="adapter"
|
||||
object-name="example.domain:name=TestBean"
|
||||
operation-name="ping"/></programlisting> Then the adapter
|
||||
only needs to be able to discover the "mbeanServer" bean. If a different
|
||||
bean name is required, then provide the "mbean-server" attribute with a
|
||||
reference.</para>
|
||||
|
||||
<para>The payload of the Message will be mapped to the parameters of the
|
||||
operation, if any. A Map-typed payload with String keys is treated as
|
||||
name/value pairs whereas a List or array would be passed as a simple
|
||||
argument list (with no explicit parameter names). If the operation
|
||||
requires a single parameter value, then the payload can represent that
|
||||
single value, and if the operation requires no parameters, then the
|
||||
payload would be ignored.</para>
|
||||
|
||||
<para>If you want to expose a channel for a single common operation to be
|
||||
invoked by Messages that need not contain headers, then that option works
|
||||
well.</para>
|
||||
</section>
|
||||
|
||||
<section id="jmx-operation-invoking-outbound-gateway">
|
||||
<title>Operation Invoking outbound Gateway</title>
|
||||
|
||||
<para>Similar to <emphasis>operation-invoking-channel-adapter</emphasis>
|
||||
Spring Integration also provides
|
||||
<emphasis>operation-invoking-outbound-gateway</emphasis> which could be
|
||||
used when dealing with non-void operations and return value is required.
|
||||
Such return value will be sent as message payload to the 'reply-channel'
|
||||
specified by this Gateway. <programlisting language="xml"> <int-jmx:operation-invoking-outbound-gateway request-channel="requestChannel"
|
||||
reply-channel="replyChannel"
|
||||
object-name="org.springframework.integration.jmx.config:type=TestBean,name=testBeanGateway"
|
||||
operation-name="testWithReturn"/></programlisting> Another way of
|
||||
provideing the 'reply-channel' is by setting
|
||||
<interfacename>MessageHeaders.REPLY_CHANNEL</interfacename> Message
|
||||
Header</para>
|
||||
</section>
|
||||
|
||||
<section id="jmx-mbean-exporter">
|
||||
<title>MBean Exporter</title>
|
||||
|
||||
<para>Spring Integration components themselves may be exposed as MBeans
|
||||
when the <classname>IntegrationMBeanExporter</classname> is configured. To
|
||||
create an instance of the <classname>IntegrationMBeanExporter</classname>,
|
||||
define a bean and provide a reference to an MBeanServer and a domain name
|
||||
(if desired). The domain can be left out in which case the default domain
|
||||
is "org.springframework.integration". <programlisting language="xml"> <int-jmx:mbean-exporter default-domain="my.company.domain" server="mbeanServer"/>
|
||||
|
||||
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean">
|
||||
<property name="locateExistingServerIfPossible" value="true"/>
|
||||
</bean></programlisting> Once the exporter is defined start up your
|
||||
application with <screen>-Dcom.sun.management.jmxremote
|
||||
-Dcom.sun.management.jmxremote.port=6969
|
||||
-Dcom.sun.management.jmxremote.ssl=false
|
||||
-Dcom.sun.management.jmxremote.authenticate=false</screen>Then start
|
||||
JConsole (free with the JDK), and connect to the local process on
|
||||
<literal>localhost:6969</literal> to get a look at the management
|
||||
endpoints exposed. (The port and client are just examples to get you
|
||||
started quickly, there are other JMX clients available and some offer more
|
||||
sophisticated features than JConsole.)</para>
|
||||
|
||||
<para>The MBean exporter is orthogonal to the one provided in Spring core
|
||||
- it registers message channels and message handlers, but not itself. You
|
||||
can expose the exporter itself, and certain other components in Spring
|
||||
Integration, using the standard
|
||||
<literal><context:mbean-export/></literal> tag. The exporter has a
|
||||
couple of useful metrics attached to it, for instance a count of the
|
||||
number of active handlers and the number of queued messages (these would
|
||||
both be important if you wanted to shutdown the context without losing any
|
||||
messages).</para>
|
||||
|
||||
<section id="jmx-mbean-features">
|
||||
<title>MBean ObjectNames</title>
|
||||
|
||||
<para>All the MessageChannel, MessageHandler and MessageSource instances
|
||||
in the application are wrapped by the MBean exporter to provide
|
||||
management and monitoring features. For example, MessageChannel send The
|
||||
generated JMX object names for each component type are listed in the
|
||||
table below</para>
|
||||
|
||||
<table>
|
||||
<title />
|
||||
|
||||
<tgroup cols="2">
|
||||
<thead>
|
||||
<row>
|
||||
<entry align="center">Component Type</entry>
|
||||
|
||||
<entry align="center">ObjectName</entry>
|
||||
</row>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<row>
|
||||
<entry>MessageChannel</entry>
|
||||
|
||||
<entry>org.springframework.integration:type=MessageChannel,name=<channelName></entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>MessageSource</entry>
|
||||
|
||||
<entry>org.springframework.integration:type=MessageSource,name=<channelName>,bean=<source></entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>MessageHandler</entry>
|
||||
|
||||
<entry>org.springframework.integration:type=MessageSource,name=<channelName>,bean=<source></entry>
|
||||
</row>
|
||||
</tbody>
|
||||
</tgroup>
|
||||
</table>
|
||||
|
||||
<para>The "bean"<literal /> attribute in the object names for sources
|
||||
and handlers takes one of the values in the table below</para>
|
||||
|
||||
<table>
|
||||
<title />
|
||||
|
||||
<tgroup cols="2">
|
||||
<thead>
|
||||
<row>
|
||||
<entry align="center">Bean Value</entry>
|
||||
|
||||
<entry align="center">Description</entry>
|
||||
</row>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<row>
|
||||
<entry>endpoint</entry>
|
||||
|
||||
<entry>The bean name of the enclosing endpoint (e.g.
|
||||
<service-activator>) if there is one</entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>anonymous</entry>
|
||||
|
||||
<entry>An indication that the enclosing endpoint didn't have a
|
||||
user-specified bean name, so the JMX name is the input channel
|
||||
name</entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>internal</entry>
|
||||
|
||||
<entry>For well-known Spring Integration default
|
||||
components</entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>handler</entry>
|
||||
|
||||
<entry>None of the above: fallback to the
|
||||
<literal>toString()</literal> of the object being monitored
|
||||
(handler or source)</entry>
|
||||
</row>
|
||||
</tbody>
|
||||
</tgroup>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section id="jmx-channel-features">
|
||||
<title>MessageChannel MBean Features</title>
|
||||
|
||||
<para>Message channels report metrics according to their concrete type.
|
||||
If you are looking at a <classname>DirectChannel</classname> you will
|
||||
see statistics for the send operation. If it is a
|
||||
<classname>QueueChannel</classname> you will also see statistics for the
|
||||
receive operation. In both cases there are some metrics that are simple
|
||||
counters (message count and error count), and some that are estimates of
|
||||
averages of interesting quantities. The algorithms used to calculate
|
||||
these estimates are described briefly in the table below:</para>
|
||||
|
||||
<table>
|
||||
<title />
|
||||
|
||||
<tgroup cols="3">
|
||||
<thead>
|
||||
<row>
|
||||
<entry align="center">Metric Type</entry>
|
||||
|
||||
<entry align="center">Example</entry>
|
||||
|
||||
<entry align="center">Algorithm</entry>
|
||||
</row>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
<row>
|
||||
<entry>Count</entry>
|
||||
|
||||
<entry>Send Count</entry>
|
||||
|
||||
<entry>Simple incrementer. Increase by one when an event
|
||||
occurs.</entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>Duration</entry>
|
||||
|
||||
<entry>Send Duration (method execution time in
|
||||
milliseconds)</entry>
|
||||
|
||||
<entry>Exponential Moving Average with decay factor 10. Average
|
||||
of the method execution time over roughly the last 10
|
||||
measurements.</entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>Rate</entry>
|
||||
|
||||
<entry>Send Rate (number of operations per second)</entry>
|
||||
|
||||
<entry>Inverse of Exponential Moving Average of the interval
|
||||
between events with decay in time (lapsing over 60 seconds) and
|
||||
per measurement (last 10 events).</entry>
|
||||
</row>
|
||||
|
||||
<row>
|
||||
<entry>Ratio</entry>
|
||||
|
||||
<entry>Send Error Ratio (ratio of errors to total sends)</entry>
|
||||
|
||||
<entry>Estimate the success ratio as the Exponential Moving
|
||||
Average of the series composed of values 1 for success and 0 for
|
||||
failure (decaying as per the rate measurement over time and
|
||||
events). Error ratio is 1 - success ratio.</entry>
|
||||
</row>
|
||||
</tbody>
|
||||
</tgroup>
|
||||
</table>
|
||||
|
||||
<para>A feature of the time-based average estimates is that they decay
|
||||
with time if no new measurements arrive. To help interpret the behaviour
|
||||
over time, the time (in seconds) since the last measurement is also
|
||||
exposed as a metric.</para>
|
||||
|
||||
<para>There are two basic exponential models: decay per measurement
|
||||
(appropriate for duration and anything where the number of measurements
|
||||
is part of the metric), and decay per time unit (more suitable for rate
|
||||
measurements where the time in between measurements is part of the
|
||||
metric). Both models depend on the fact that <screen>S(n) = sum(i=0,i=n) w(i) x(i)</screen>
|
||||
has a special form when <literal>w(i) = r^i</literal>, with
|
||||
<literal>r=constant</literal>: <screen>S(n) = x(n) + r S(n-1)</screen>(so
|
||||
you only have to store <literal>S(n-1)</literal>, not the whole series
|
||||
<literal>x(i)</literal>, to generate a new metric estimate from the last
|
||||
measurement). The algorithms used in the duration metrics use
|
||||
<literal>r=exp(-1/M)</literal> with <literal>M=10</literal>. The net
|
||||
effect is that the estimate <literal>S(n)</literal> is more heavily
|
||||
weighted to recent measurements and is composed roughly of the last
|
||||
<literal>M</literal> measurements. So <literal>M</literal> is the
|
||||
"window" or lapse rate of the estimate In the case of the vanilla moving
|
||||
average, <literal>i</literal> is a counter over the number of
|
||||
measurements. In the case of the rate we interpret <literal>i</literal>
|
||||
as the elapsed time, or a combination of elapsed time and a counter (so
|
||||
the metric estimate contains contributions roughly from the last
|
||||
<literal>M</literal> measurements and the last <literal>T</literal>
|
||||
seconds).</para>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
250
src/reference/docbook/mail.xml
Normal file
@@ -0,0 +1,250 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="mail"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Mail Support</title>
|
||||
|
||||
<section id="mail-outbound">
|
||||
<title>Mail-Sending Channel Adapter</title>
|
||||
<para>
|
||||
Spring Integration provides support for outbound email with the
|
||||
<classname>MailSendingMessageHandler</classname>. It delegates to a configured instance of Spring's
|
||||
<interfacename>JavaMailSender</interfacename>:
|
||||
<programlisting language="java"> JavaMailSender mailSender = context.getBean("mailSender", JavaMailSender.class);
|
||||
|
||||
MailSendingMessageHandler mailSendingHandler = new MailSendingMessageHandler(mailSender);</programlisting>
|
||||
<classname>MailSendingMessageHandler</classname> has various mapping strategies that use Spring's
|
||||
<interfacename>MailMessage</interfacename> abstraction. If the received Message's payload is already
|
||||
a <classname>MailMessage</classname> instance, it will be sent directly.
|
||||
Therefore, it is generally recommended to precede this
|
||||
consumer with a Transformer for non-trivial MailMessage construction requirements. However, a few simple
|
||||
Message mapping strategies are supported out-of-the-box. For example, if the message payload is a byte array,
|
||||
then that will be mapped to an attachment. For simple text-based emails, you can provide a String-based
|
||||
Message payload. In that case, a MailMessage will be created with that String as the text content. If you
|
||||
are working with a Message payload type whose toString() method returns appropriate mail text content, then
|
||||
consider adding Spring Integration's <emphasis>ObjectToStringTransformer</emphasis> prior to the outbound
|
||||
Mail adapter (see the example within <xref linkend="transformer-namespace"/> for more detail).
|
||||
</para>
|
||||
<para>
|
||||
The outbound MailMessage may also be configured with certain values from the
|
||||
<classname>MessageHeaders</classname>. If available, values will be mapped to the outbound mail's
|
||||
properties, such as the recipients (TO, CC, and BCC), the from/reply-to, and the subject. The header names are
|
||||
defined by the following constants:
|
||||
<programlisting language="java"> MailHeaders.SUBJECT
|
||||
MailHeaders.TO
|
||||
MailHeaders.CC
|
||||
MailHeaders.BCC
|
||||
MailHeaders.FROM
|
||||
MailHeaders.REPLY_TO</programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<classname>MailHeaders</classname> also allows you to override corresponding <classname>MailMessage</classname> values.
|
||||
For example: If <classname>MailMessage.to</classname> is set to 'foo@bar.com' and <classname>MailHeaders.TO</classname>
|
||||
Message header is provided it will take precedence and override the corresponding value in <classname>MailMessage</classname>
|
||||
</note>
|
||||
</section>
|
||||
|
||||
<section id="mail-inbound">
|
||||
<title>Mail-Receiving Channel Adapter</title>
|
||||
<para>
|
||||
Spring Integration also provides support for inbound email with the
|
||||
<classname>MailReceivingMessageSource</classname>. It delegates to a configured instance of Spring
|
||||
Integration's own <interfacename>MailReceiver</interfacename> interface, and there are two implementations:
|
||||
<classname>Pop3MailReceiver</classname> and <classname>ImapMailReceiver</classname>. The easiest way to
|
||||
instantiate either of these is by passing the 'uri' for a Mail store to the receiver's constructor. For example:
|
||||
<programlisting language="java"><![CDATA[ MailReceiver receiver = new Pop3MailReceiver("pop3://usr:pwd@localhost/INBOX");
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Another option for receiving mail is the IMAP "idle" command (if supported by the mail server you are using).
|
||||
Spring Integration provides the <classname>ImapIdleChannelAdapter</classname> which is itself a Message-producing
|
||||
endpoint. It delegates to an instance of the <classname>ImapMailReceiver</classname> but enables asynchronous
|
||||
reception of Mail Messages. There are examples in the next section of configuring both types of inbound Channel
|
||||
Adapter with Spring Integration's namespace support in the 'mail' schema.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="mail-namespace">
|
||||
<title>Mail Namespace Support</title>
|
||||
<para>
|
||||
Spring Integration provides a namespace for mail-related configuration. To use it, configure the following schema
|
||||
locations.<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/integration/mail
|
||||
http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd">]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To configure an outbound Channel Adapter, provide the channel to receive from, and the MailSender:
|
||||
<programlisting language="xml"><![CDATA[<int-mail:outbound-channel-adapter channel="outboundMail"
|
||||
mail-sender="mailSender"/>]]></programlisting>
|
||||
Alternatively, provide the host, username, and password:
|
||||
<programlisting language="xml"><![CDATA[<int-mail:outbound-channel-adapter channel="outboundMail"
|
||||
host="somehost" username="someuser" password="somepassword"/>]]></programlisting>
|
||||
<note>
|
||||
Keep in mind, as with any outbound Channel Adapter, if the referenced channel is a PollableChannel, a
|
||||
<poller> sub-element should be provided with either an interval-trigger or cron-trigger.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
To configure an Inbound Channel Adapter, you have the choice between polling or event-driven (assuming your
|
||||
mail server supports IMAP IDLE - if not, then polling is the only option). A polling Channel Adapter simply
|
||||
requires the store URI and the channel to send inbound Messages to. The URI may begin with "pop3" or "imap":
|
||||
<programlisting language="xml"><![CDATA[<int-mail:inbound-channel-adapter id="imapAdapter"
|
||||
store-uri="imaps://[username]:[password]@imap.gmail.com/INBOX"
|
||||
java-mail-properties="javaMailProperties"
|
||||
channel="recieveChannel"
|
||||
should-delete-messages="true"
|
||||
should-mark-messages-as-read="true"
|
||||
auto-startup="true">
|
||||
<int:poller max-messages-per-poll="1" fixed-rate="5000"/>
|
||||
</int-mail:inbound-channel-adapter>]]></programlisting>
|
||||
If you do have IMAP idle support, then you may want to configure the "imap-idle-channel-adapter" element instead.
|
||||
Since the "idle" command enables event-driven notifications, no poller is necessary for this adapter. It will
|
||||
send a Message to the specified channel as soon as it receives the notification that new mail is available:
|
||||
<programlisting language="xml"><![CDATA[<int-mail:imap-idle-channel-adapter id="customAdapter"
|
||||
store-uri="imaps://[username]:[password]@imap.gmail.com/INBOX"
|
||||
channel="recieveChannel"
|
||||
auto-startup="true"
|
||||
should-delete-messages="false"
|
||||
should-mark-messages-as-read="true"
|
||||
java-mail-properties="javaMailProperties"/>]]></programlisting>
|
||||
... where <emphasis>javaMailProperties</emphasis> could be provided by creating and populating
|
||||
a regular <classname>java.utils.Properties</classname> object. For example via <emphasis>util</emphasis> namespace
|
||||
provided by Spring.
|
||||
<important>
|
||||
If your username contains the '@' character use '%40' instead of '@' to avoid parsing errors from the underlying JavaMail API.
|
||||
</important>
|
||||
<programlisting language="xml"><![CDATA[<util:properties id="javaMailProperties">
|
||||
<prop key="mail.imap.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
|
||||
<prop key="mail.imap.socketFactory.fallback">false</prop>
|
||||
<prop key="mail.store.protocol">imaps</prop>
|
||||
<prop key="mail.debug">false</prop>
|
||||
</util:properties>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para><emphasis>IMAP IDLE and lost connection</emphasis></para>
|
||||
|
||||
<para>
|
||||
When using IMAP IDLE channel adapter there might be situations where connection to the server may be lost
|
||||
(e.g., network failure) and since Java Mail documentation explicitly states that the actual IMAP API is EXPERIMENTAL it is
|
||||
important to understand the differences in the API and how to deal with them when configuring IMAP IDLE adapters.
|
||||
Currently Spring Integration Mail adapters was tested with Java Mail 1.4.1 and Java Mail 1.4.3 and depending on which one
|
||||
is used special attention must be payed to some of the java mail properties that needs to be set with regard to auto-reconnect.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>
|
||||
The following behavior was observed with GMAIL but should provide you with some tips on how to solve re-connect
|
||||
issue with other providers, however feedback is always welcome. Again, below notes are based on GMAIL.
|
||||
</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
With Java Mail 1.4.1 if <code>mail.imaps.timeout</code> property is set for a relatively short period of time (e.g., ~ 5 min)
|
||||
then <code>IMAPFolder.idle()</code> will throw <classname>FolderClosedException</classname> after this timeout.
|
||||
However if this property is not set (should be indefinite) the behavior that was observed is that <code>IMAPFolder.idle()</code>
|
||||
method never returns nor it throws an exception. It will however reconnect automatically if connection was lost for a short
|
||||
period of time (e.g., under 10 min), but if connection was lost for a long period of time (e.g., over 10 min), then
|
||||
<code>IMAPFolder.idle()</code> will not throw <classname>FolderClosedException</classname> nor it will re-establish connection
|
||||
and will remain in the blocked state indefinitely, thus leaving you no possibility to reconnect without restarting the adapter.
|
||||
So the only way to make re-connect to work with Java Mail 1.4.1 is to set <code>mail.imaps.timeout</code> property explicitly
|
||||
to some value, but it also means that such value shoudl be relatively short (under 10 min) and the connection should be
|
||||
re-estabished relatively quickly. Again, it may be different with other providers.
|
||||
|
||||
With Java Mail 1.4.3 there was significant improvements to the API ensuring that there will always be a condition which
|
||||
will force <code>IMAPFolder.idle()</code> method to return via <classname>StoreClosedException</classname> or
|
||||
<classname>FolderClosedException</classname> or simply return, thus allowing us to proceed with auto-reconnect.
|
||||
Currently auto-reconnect will run infinitely making attempts to reconnect every 10 sec.
|
||||
</para>
|
||||
|
||||
<important>
|
||||
In both configurations <code>channel</code> and <code>should-delete-messages</code> are the <emphasis>REQUIRED</emphasis>
|
||||
attributes. The important thing to understand is why <code>should-delete-messages</code> is required.
|
||||
The issue is with the POP3 protocol, which does NOT have any knowledge of messages that were READ. It can only know what's been read
|
||||
within a single session. This means that when your POP3 mail adapter is running, emails are successfully consumed as as they become available during each poll
|
||||
and no single email message will be delivered more then once. However, as soon as you restart your adapter and begin a new session
|
||||
all the email messages that might have been retrieved in the previous session will be retrieved again. That is the nature of POP3. Some might argue
|
||||
that <code>should-delete-messages</code> should be TRUE by default. In other words, there are two valid and mutually exclusive use cases
|
||||
which make it very hard to pick a single "best" default. You may want to configure your adapter as the only email receiver in which
|
||||
case you want to be able to restart such adapter without fear that messages that were delivered before will not be redelivered again.
|
||||
In this case setting <code>should-delete-messages</code> to TRUE would make most sense. However, you may have another use case where
|
||||
you may want to have multiple adapters that simply monitor email servers and their content. In other words you just want to 'peek but not touch'.
|
||||
Then setting <code>should-delete-messages</code> to FALSE would be much more appropriate. So since it is hard to choose what should be
|
||||
the right default value for the <code>should-delete-messages</code> attribute, we simply made it a required attribute, to be set by the user.
|
||||
Leaving it up to the user also means, you will be less likely to end up with unintended behavior.
|
||||
</important>
|
||||
|
||||
<note>When configuring a polling email adapter's <emphasis>should-mark-messages-as-read</emphasis> attribute,
|
||||
be aware of the protocol you are configuring to retrieve messages. For example POP3 does not support this flag
|
||||
which means setting it to either value will have no effect as messages will NOT be marked as read.</note>
|
||||
|
||||
<para>
|
||||
When using the namespace support, a <emphasis>header-enricher</emphasis> Message Transformer is also available.
|
||||
This simplifies the application of the headers mentioned above to any Message prior to sending to the
|
||||
Mail-sending Channel Adapter.
|
||||
<programlisting language="xml"><![CDATA[<int-mail:header-enricher subject="Example Mail"
|
||||
to="to@example.org"
|
||||
cc="cc@example.org"
|
||||
bcc="bcc@example.org"
|
||||
from="from@example.org"
|
||||
reply-to="replyTo@example.org"
|
||||
overwrite="false"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Finally, the <imap-idle-channel-adapter/> also accepts the 'error-channel' attribute.
|
||||
If a downstream exception is thrown and an 'error-channel' is specified,
|
||||
a MessagingException message containing the failed message and original exception, will be sent to this channel.
|
||||
Otherwise, if the downstream channels are synchronous, any such exception will simply be logged as a
|
||||
warning by the channel adapter.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="mail-filtering">
|
||||
<title>Email Message Filtering</title>
|
||||
<para>
|
||||
Very often you may encounter a requirement to filter incoming messages
|
||||
(e.g., You want to only read emails that have 'Spring Integration' in the <emphasis>Subject</emphasis> line). This
|
||||
could be easily accomplished by connecting Inbound Mail adapter with an expression-based <emphasis>Filter</emphasis>. Although it would work, there is a
|
||||
downside to this approach. Since messages would be filtered after going through inbound mail adapter all such messages would be marked as read (SEEN) or
|
||||
Un-read (depending on the value of <code>should-mark-messages-as-read</code> attribute). However in reality what would be more useful is to mark messages
|
||||
as SEEN only if they passed the filtering criteria. This is very similar to looking at your email client while scrolling through all the
|
||||
messages in the preview pane, but only flagging messages as SEEN that were actually opened and read.
|
||||
</para>
|
||||
<para>
|
||||
In Spring Integration 2.0.4 we've introduced <code>mail-filter-expression</code> attribute on <code>inbound-channel-adapter</code> and
|
||||
<code>imap-idle-channel-adapter</code>. This attribute allows you to provide an expression which is a combination of SpEL and Regular Expression.
|
||||
For example if you would like to read only emails that contain 'Spring Integration' in the Subject line, you would configure <code>mail-filter-expression</code> attribute
|
||||
like this this: <code>mail-filter-expression="subject matches '(?i).*Spring Integration.*"</code>
|
||||
</para>
|
||||
<para>
|
||||
Since <classname>javax.mail.internet.MimeMessage</classname> is the root context of SpEL Evaluation Context, you can filter on any value available
|
||||
through MimeMessage including the actual body of the message. This one is particularly important since reading the body of the message would
|
||||
typically result in such message to be marked as SEEN by default, but since we now setting PEAK flag of every incomming message to 'true', only
|
||||
messages that were explicitly marked as SEEN will be seen as read.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
So in the below example only messages that match the filter expression will be output by this adapter and only those messages will be marked as SEEN.
|
||||
In this case based on the <code>mail-filter-expression</code> only messages that contain 'Spring Integration' in the subject line will be
|
||||
produced by this adapter.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-mail:imap-idle-channel-adapter id="customAdapter"
|
||||
store-uri="imaps://some_google_address:${password}@imap.gmail.com/INBOX"
|
||||
channel="receiveChannel"
|
||||
should-mark-messages-as-read="true"
|
||||
java-mail-properties="javaMailProperties"
|
||||
mail-filter-expression="subject matches '(?i).*Spring Integration.*'"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Another reasonable question is what happens on the next poll, or idle event, or what happens when such adapter is restarted.
|
||||
Will there be a potential duplication of massages to be filtered? In other words if on the last retrieval where you had 5 new messages and only 1 passed
|
||||
the filter what would happen with the other 4. Would they go through the filtering logic again on the next poll or idle? After all they were not marked
|
||||
as SEEN. The actual answer is no. They would not be subject of duplicate processing due to another flag (RECENT) that is set by the Email server and
|
||||
is used by Spring Integration mail search filter. Folder implementations set this flag to indicate that this message is new to this folder, that is,
|
||||
it has arrived since the last time this folder was opened. In other while our adapter may peek at the email it also lets the email server know that
|
||||
such email was touched and therefore will be marked as RECENT by the email server.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
9
src/reference/docbook/message-construction.xml
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="messaging-construction-chapter"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Construction</title>
|
||||
|
||||
<xi:include href="./message.xml"/>
|
||||
|
||||
</chapter>
|
||||
70
src/reference/docbook/message-history.xml
Normal file
@@ -0,0 +1,70 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="message-history"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message History</title>
|
||||
<para>
|
||||
The key benefit of a messaging architecture is loose coupling where participating components do not maintain any awareness about one another. This fact
|
||||
alone makes your application extremely flexible, allowing you to change components without affecting the rest of the flow, change messaging routes,
|
||||
message consuming styles (polling vs event driven), and so on.
|
||||
However, this unassuming style of architecture could prove to be difficult when things go wrong. When debugging,
|
||||
you would probably like to get as much information about the message as you can (its origin, channels it has traversed, etc.)
|
||||
</para>
|
||||
<para>
|
||||
Message History is one of those patterns that helps by giving you an option to maintain some level of awareness of a
|
||||
message path either for debugging purposes or to maintain an audit trail.
|
||||
Spring integration provides a simple way to configure your message flows to maintain the Message History by adding a header to the
|
||||
Message and updating that header every time a message passes through a tracked component.
|
||||
</para>
|
||||
|
||||
<section id="message-history-config">
|
||||
<title>Message History Configuration</title>
|
||||
<para>
|
||||
To enable Message History all you need is to define the <code>message-history</code> element in your configuration.
|
||||
<programlisting language="xml"><![CDATA[<int:message-history/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Now every named component (component that has an 'id' defined) will be tracked.
|
||||
The framework will set the 'history' header in your Message. Its value is very simple - <classname>List<Properties></classname>.
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="xml"><![CDATA[<int:gateway id="sampleGateway"
|
||||
service-interface="org.springframework.integration.history.sample.SampleGateway"
|
||||
default-request-channel="bridgeInChannel"/>
|
||||
|
||||
<int:chain id="sampleChain" input-channel="chainChannel" output-channel="filterChannel">
|
||||
<int:header-enricher>
|
||||
<int:header name="baz" value="baz"/>
|
||||
</int:header-enricher>
|
||||
</int:chain>]]></programlisting>
|
||||
|
||||
The above configuration will produce a very simple Message History structure:
|
||||
<programlisting language="java"><![CDATA[[{name=sampleGateway, type=gateway, timestamp=1283281668091},
|
||||
{name=sampleChain, type=chain, timestamp=1283281668094}]]]></programlisting>
|
||||
|
||||
To get access to Message History all you need is access the MessageHistory header. For example:
|
||||
<programlisting language="java"><![CDATA[Iterator<Properties> historyIterator =
|
||||
message.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator();
|
||||
assertTrue(historyIterator.hasNext());
|
||||
Properties gatewayHistory = historyIterator.next();
|
||||
assertEquals("sampleGateway", gatewayHistory.get("name"));
|
||||
assertTrue(historyIterator.hasNext());
|
||||
Properties chainHistory = historyIterator.next();
|
||||
assertEquals("sampleChain", chainHistory.get("name"));]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
You might not want to track all of the components. To limit the history to certain components based on their names,
|
||||
all you need is provide the <code>tracked-components</code> attribute and specify
|
||||
a comma-delimited list of component names and/or patterns that match the components you want to track.
|
||||
<programlisting language="xml"><![CDATA[<int:message-history tracked-components="*Gateway, sample*, foo"/>]]></programlisting>
|
||||
In the above example, Message History will only be maintained for all of the components that end with 'Gateway', start with 'sample',
|
||||
or match the name 'foo' exactly.
|
||||
</para>
|
||||
<note>
|
||||
Remember that by definition the Message History header is immutable (you can't re-write history, although some try). Therefore, when writing
|
||||
Message History values, the components are either creating brand new Messages (when the component is an origin), or they are copying the
|
||||
history from a request Message, modifying it and setting the new list on a reply Message. In either case, the values can be appended even
|
||||
if the Message itself is crossing thread boundaries. That means that the history values can greatly simplify debugging in an
|
||||
asynchronous message flow.
|
||||
</note>
|
||||
</section>
|
||||
</section>
|
||||
384
src/reference/docbook/message-publishing.xml
Normal file
@@ -0,0 +1,384 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="message-publishing"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Publishing</title>
|
||||
<para>
|
||||
The AOP Message Publishing feature allows you to construct and send a message as a by-product of a method invocation. For example, imagine you
|
||||
have a component and every time the state of this component changes you would like to be notified via a Message. The easiest
|
||||
way to send such notifications would be to send a message to a dedicated channel, but how would you connect the method invocation that
|
||||
changes the state of the object to a message sending process, and how should the notification Message be structured?
|
||||
The AOP Message Publishing feature handles these responsibilities with a configuration-driven approach.
|
||||
</para>
|
||||
<section id="message-publishing-config">
|
||||
<title>Message Publishing Configuration</title>
|
||||
<para>
|
||||
Spring Integration provides two approaches: XML and Annotation-driven.
|
||||
</para>
|
||||
<section id="publisher-annotation">
|
||||
<title>Annotation-driven approach via @Publisher annotation</title>
|
||||
<para>
|
||||
The annotation-driven approach allows you to annotate any method with the <interfacename>@Publisher</interfacename> annotation,
|
||||
specifying a 'channel' attribute.
|
||||
The Message will be constructed from the return value of the method invocation and sent to a channel specified by the 'channel' attribute.
|
||||
To further manage message structure, you can also use a combination of both <interfacename>@Payload</interfacename>
|
||||
and <interfacename>@Header</interfacename> annotations.
|
||||
</para>
|
||||
<para>
|
||||
Internally this message publishing feature of Spring Integration uses both Spring AOP by defining
|
||||
<classname>PublisherAnnotationAdvisor</classname> and
|
||||
Spring 3.0's Expression Language (SpEL) support, giving you considerable flexibility and control over the structure of the
|
||||
<emphasis>Message</emphasis> it will publish.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The <classname>PublisherAnnotationAdvisor</classname> defines and binds the following variables:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>#return</emphasis> - will bind to a return value allowing you to reference it or its
|
||||
attributes (e.g., <emphasis>#return.foo</emphasis> where 'foo' is an attribute of the object bound to
|
||||
<emphasis>#return</emphasis>)</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>#exception</emphasis> - will bind to an exception if one is thrown by the method invocation.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>#args</emphasis> - will bind to method arguments, so individual arguments could be extracted by name
|
||||
(e.g., <emphasis>#args.fname</emphasis> as in the above method)</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Let's look at a couple of examples:
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="java">@Publisher
|
||||
public String defaultPayload(String fname, String lname) {
|
||||
return fname + " " + lname;
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
In the above example the Message will be constructed with the following structure:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>Message payload - will be the return type and value of the method. This is the default.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>A newly constructed message will be sent to a default publisher channel configured with an annotation post processor (see the end of this section).</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="java">@Publisher(channel="testChannel")
|
||||
public String defaultPayload(String fname, @Header("last") String lname) {
|
||||
return fname + " " + lname;
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
In this example everything is the same as above, except that we are not using a default publishing channel. Instead we are specifying
|
||||
the publishing channel via the 'channel' attribute of the <interface>@Publisher</interface> annotation.
|
||||
We are also adding a <interface>@Header</interface> annotation which results in the Message header named 'last' having the same value
|
||||
as the 'lname' method parameter. That header will be added to the newly constructed Message.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<programlisting language="java">@Publisher(channel="testChannel")
|
||||
@Payload
|
||||
public String defaultPayloadButExplicitAnnotation(String fname, @Header String lname) {
|
||||
return fname + " " + lname;
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The above example is almost identical to the previous one. The only difference here is that we are using a <interface>@Payload</interface> annotation
|
||||
on the method, thus explicitly specifying that the return value of the method should be used as the payload of the Message.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<programlisting language="java">@Publisher(channel="testChannel")
|
||||
@Payload("#return + #args.lname")
|
||||
public String setName(String fname, String lname, @Header("x") int num) {
|
||||
return fname + " " + lname;
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Here we are expanding on the previous configuration by using the Spring Expression Language in the
|
||||
<interface>@Payload</interface> annotation to further instruct
|
||||
the framework how the message should be constructed. In this particular case the message will be a concatenation of the return
|
||||
value of the method invocation and the 'lname' input argument. The Message header named 'x' will have its value determined by
|
||||
the 'num' input argument. That header will be added to the newly constructed Message.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<programlisting language="java">@Publisher(channel="testChannel")
|
||||
public String argumentAsPayload(@Payload String fname, @Header String lname) {
|
||||
return fname + " " + lname;
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
In the above example you see another usage of the <interface>@Payload</interface> annotation. Here we are annotating a method argument
|
||||
which will become the payload of the newly constructed message.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
As with most other annotation-driven features in Spring, you will need to register a post-processor
|
||||
(<classname>PublisherAnnotationBeanPostProcessor</classname>).
|
||||
<programlisting language="xml"><bean class="org.springframework.integration.aop.PublisherAnnotationBeanPostProcessor"/></programlisting>
|
||||
You can instead use namespace support for a more concise configuration:
|
||||
|
||||
<programlisting language="xml"><int:annotation-config default-publisher-channel="defaultChannel"/></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Similar to other Spring annotations (@Component, @Scheduled, etc.), <classname>@Publisher</classname> can also be used as a meta-annotation.
|
||||
That means you can define your own annotations
|
||||
that will be treated in the same way as the <classname>@Publisher</classname> itself.
|
||||
<programlisting language="java"><![CDATA[@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Publisher(channel="auditChannel")
|
||||
public @interface Audit {
|
||||
}]]></programlisting>
|
||||
Here we defined the <classname>@Audit</classname> annotation which itself is annotated with <classname>@Publisher</classname>.
|
||||
Also note that you can define a <code>channel</code>
|
||||
attribute on the meta-annotation thus encapsulating the behavior of where messages will be sent inside of this annotation.
|
||||
|
||||
Now you can annotate any method:
|
||||
<programlisting language="java"><![CDATA[@Audit
|
||||
public String test() {
|
||||
return "foo";
|
||||
}]]></programlisting>
|
||||
|
||||
In the above example every invocation of the <code>test()</code> method will result in a Message with a payload created from its return value.
|
||||
Each Message will be sent to the channel named <emphasis>auditChannel</emphasis>. One of the benefits of this technique is that you can
|
||||
avoid the duplication of the same channel name across multiple annotations. You also can provide a level of indirection between your own,
|
||||
potentially domain-specific annotations and those provided by the framework.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
You can also annotate the class which would mean that the properties of this annotation will be applied on every public method of that class.
|
||||
|
||||
<programlisting language="java"><![CDATA[@Audit
|
||||
static class BankingOperationsImpl implements BankingOperations {
|
||||
|
||||
public String debit(String amount) {
|
||||
. . .
|
||||
}
|
||||
|
||||
public String credit(String amount) {
|
||||
. . .
|
||||
}
|
||||
}]]></programlisting>
|
||||
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="aop-based-interceptor">
|
||||
<title>XML-based approach via the <publishing-interceptor> element</title>
|
||||
<para>
|
||||
The XML-based approach allows you to configure the same AOP-based Message Publishing functionality with
|
||||
simple namespace-based configuration of a <classname>MessagePublishingInterceptor</classname>.
|
||||
It certainly has some benefits over the annotation-driven approach since it
|
||||
allows you to use AOP pointcut expressions, thus possibly intercepting multiple methods at once or
|
||||
intercepting and publishing methods to which you don't have the source code.
|
||||
</para>
|
||||
<para>
|
||||
To configure Message Publishing via XML, you only need to do the following two things:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>Provide configuration for <classname>MessagePublishingInterceptor</classname>
|
||||
via the <code><publishing-interceptor></code> XML element.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Provide AOP configuration to apply the <classname>MessagePublishingInterceptor</classname> to managed objects.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="xml"><![CDATA[<aop:config>
|
||||
<aop:advisor advice-ref="interceptor" pointcut="bean(testBean)" />
|
||||
</aop:config>
|
||||
<publishing-interceptor id="interceptor" default-channel="defaultChannel">
|
||||
<method pattern="echo" payload="'Echoing: ' + #return" channel="echoChannel">
|
||||
<header name="foo" value="bar"/>
|
||||
</method>
|
||||
<method pattern="repl*" payload="'Echoing: ' + #return" channel="echoChannel">
|
||||
<header name="foo" expression="'bar'.toUpperCase()"/>
|
||||
</method>
|
||||
<method pattern="echoDef*" payload="#return"/>
|
||||
</publishing-interceptor>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
As you can see the <code><publishing-interceptor></code> configuration looks rather similar to the Annotation-based approach,
|
||||
and it also utilizes the power of the Spring 3.0 Expression Language.
|
||||
</para>
|
||||
<para>
|
||||
In the above example the execution of the <code>echo</code> method of a <code>testBean</code> will
|
||||
render a <emphasis>Message</emphasis> with the following structure:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>The Message payload will be of type String with the content "Echoing: [value]" where <code>value</code> is the value
|
||||
returned by an executed method.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>The Message will have a header with the name "foo" and value "bar".</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>The Message will be sent to <code>echoChannel</code>.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The second method is very similar to the first. Here every method that begins with 'repl' will render a Message with the following structure:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>The Message payload will be the same as in the above sample</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>The Message will have a header named "foo" whose value is the result of the SpEL expression <code>'bar'.toUpperCase()</code> .</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>The Message will be sent to <code>echoChannel</code>.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The second method, mapping the execution of any method that begins with <code>echoDef</code> of <code>testBean</code>, will produce a
|
||||
Message with the following structure.
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>The Message payload will be the value returned by an executed method.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Since the <code>channel</code> attribute is not provided explicitly, the Message will be sent to the
|
||||
<code>defaultChannel</code> defined by the <emphasis>publisher</emphasis>.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
For simple mapping rules you can rely on the <emphasis>publisher</emphasis> defaults. For example:
|
||||
<programlisting language="xml">
|
||||
<publishing-interceptor id="anotherInterceptor"/>
|
||||
</programlisting>
|
||||
This will map the return value of every method that matches the pointcut expression to a payload and will be sent to a <emphasis>default-channel</emphasis>.
|
||||
If the <emphasis>defaultChannel</emphasis>is not specified (as above) the messages will be sent to the global <emphasis>nullChannel</emphasis>.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Async Publishing</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
One important thing to understand is that publishing occurs in the same thread as your component's execution. So by default in is synchronous.
|
||||
This means that the entire message flow would have to wait until the publisher's flow completes.
|
||||
However, quite often you want the complete opposite and that is to use this Message publishing feature to initiate asynchronous sub-flows.
|
||||
For example, you might host a service (HTTP, WS etc.) which receives a remote request.You may want to send this request internally into a
|
||||
process that might take a while. However you may also want to reply to the user right away. So, instead of sending inbound
|
||||
requests for processing via the output channel (the conventional way), you can simply use 'output-channel' or a 'replyChannel' header
|
||||
to send a simple acknowledgment-like reply back to the caller while using the Message publisher feature to initiate a complex flow.
|
||||
</para>
|
||||
<para>
|
||||
EXAMPLE:
|
||||
Here is the simple service that receives a complex payload, which needs to be sent further for processing, but it
|
||||
also needs to reply to the caller with a simple acknowledgment.
|
||||
<programlisting language="java"><![CDATA[public String echo(Object complexPayload) {
|
||||
return "ACK";
|
||||
}]]></programlisting>
|
||||
So instead of hooking up the complex flow to the output channel we use the Message publishing feature instead. We configure it to create a
|
||||
new Message using the input argument of the service method (above) and send that to the 'localProcessChannel'. And to make sure this sub-flow
|
||||
is asynchronous all we need to do is send it to any type of asynchronous channel (ExecutorChannel in this example).
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="inputChannel" output-channel="outputChannel" ref="sampleservice"/>
|
||||
|
||||
<bean id="sampleservice" class="test.SampleService"/>
|
||||
|
||||
<aop:config>
|
||||
<aop:advisor advice-ref="interceptor" pointcut="bean(sampleservice)" />
|
||||
</aop:config>
|
||||
|
||||
<int:publishing-interceptor id="interceptor" >
|
||||
<int:method pattern="echo" payload="#args[0]" channel="localProcessChannel">
|
||||
<int:header name="sample_header" expression="'some sample value'"/>
|
||||
</int:method>
|
||||
</int:publishing-interceptor>
|
||||
|
||||
<int:channel id="localProcessChannel">
|
||||
<int:dispatcher task-executor="executor"/>
|
||||
</int:channel>
|
||||
|
||||
<task:executor id="executor" pool-size="5"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Another way of handling this type of scenario is with a wire-tap.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="scheduled-producer">
|
||||
<title>Producing and publishing messages based on a scheduled trigger</title>
|
||||
<para>
|
||||
In the above sections we looked at the Message publishing feature of Spring Integration which constructs and publishes messages as by-products of Method invocations.
|
||||
However in those cases, you are still responsible for invoking the method.
|
||||
In Spring Integration 2.0 we've added another related useful feature: support for scheduled Message producers/publishers via the new "expression" attribute
|
||||
on the 'inbound-channel-adapter' element. Scheduling could be based on several triggers, any one of which may be configured on the 'poller' sub-element.
|
||||
Currently we support <code>cron</code>, <code>fixed-rate</code>, <code>fixed-delay</code> as well as any custom trigger implemented by you and
|
||||
referenced by the 'trigger' attribute value.
|
||||
</para>
|
||||
<para>
|
||||
As mentioned above, support for scheduled producers/publishers is provided via the <emphasis><inbound-channel-adapter></emphasis> xml element.
|
||||
Let's look at couple of examples:
|
||||
</para>
|
||||
<para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:inbound-channel-adapter id="fixedDelayProducer"
|
||||
expression="'fixedDelayTest'"
|
||||
channel="fixedDelayChannel">
|
||||
<int:poller fixed-delay="1000"/>
|
||||
</int:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
In the above example an inbound Channel Adapter will be created which will construct a Message with its payload being the result of the expression
|
||||
defined in the <code>expression</code> attribute. Such messages will be created and sent every time the delay specified by the <code>fixed-delay</code> attribute occurs.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:inbound-channel-adapter id="fixedRateProducer"
|
||||
expression="'fixedRateTest'"
|
||||
channel="fixedRateChannel">
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
This example is very similar to the previous one, except that we are using the <code>fixed-rate</code> attribute which will allow us to send messages at a fixed rate (measuring from the start time of each task).
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:inbound-channel-adapter id="cronProducer"
|
||||
expression="'cronTest'"
|
||||
channel="cronChannel">
|
||||
<int:poller cron="7 6 5 4 3 ?"/>
|
||||
</int:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
This example demonstrates how you can apply a Cron trigger with a value specified in the <code>cron</code> attribute.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:inbound-channel-adapter id="headerExpressionsProducer"
|
||||
expression="'headerExpressionsTest'"
|
||||
channel="headerExpressionsChannel"
|
||||
auto-startup="false">
|
||||
<int:poller fixed-delay="5000"/>
|
||||
<int:header name="foo" expression="6 * 7"/>
|
||||
<int:header name="bar" value="x"/>
|
||||
</int:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
Here you can see that in a way very similar to the Message publishing feature we are enriching a newly constructed Message with
|
||||
extra Message headers which can take scalar values or the results of evaluating Spring expressions.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
If you need to implement your own custom trigger you can use the <code>trigger</code> attribute to provide a reference to any spring configured
|
||||
bean which implements the <classname>org.springframework.scheduling.Trigger</classname> interface.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:inbound-channel-adapter id="triggerRefProducer"
|
||||
expression="'triggerRefTest'" channel="triggerRefChannel">
|
||||
<int:poller trigger="customTrigger"/>
|
||||
</int:inbound-channel-adapter>
|
||||
|
||||
<beans:bean id="customTrigger" class="org.springframework.scheduling.support.PeriodicTrigger">
|
||||
<beans:constructor-arg value="9999"/>
|
||||
</beans:bean>]]></programlisting>
|
||||
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
</chapter>
|
||||
14
src/reference/docbook/message-routing.xml
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="messaging-routing-chapter"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Routing</title>
|
||||
|
||||
<xi:include href="./router.xml"/>
|
||||
<xi:include href="./filter.xml"/>
|
||||
<xi:include href="./splitter.xml"/>
|
||||
<xi:include href="./aggregator.xml"/>
|
||||
<xi:include href="./resequencer.xml"/>
|
||||
<xi:include href="./chain.xml"/>
|
||||
|
||||
</chapter>
|
||||
97
src/reference/docbook/message-store.xml
Normal file
@@ -0,0 +1,97 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="message-store"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Store</title>
|
||||
<para>
|
||||
Enterprise Integration Patterns (EIP) identifies several patterns that have the capability to buffer messages. For example,
|
||||
an <emphasis>Aggregator</emphasis> buffers messages until they can be released and a <emphasis>QueueChannel</emphasis> buffers
|
||||
messages until consumers explicitly receive those messages from that channel.
|
||||
Because of the failures that can occur at any point within your message flow, EIP components that buffer
|
||||
messages also introduce a point where messages could be lost.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
To mitigate the risk of losing Messages, EIP defines the <ulink url="http://eaipatterns.com/MessageStore.html">Message Store</ulink> pattern which allows
|
||||
EIP components to store <emphasis>Messages</emphasis> typically in some type of persistent store (e.g. RDBMS).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration provides support for the <emphasis>Message Store</emphasis> pattern by
|
||||
a) defining a <classname>org.springframework.integration.store.MessageStore</classname> strategy interface,
|
||||
b) providing several implementations of this interface, and
|
||||
c) exposing a <code>message-store</code> attribute on all components that have the capability to buffer messages
|
||||
so that you can inject any instance that implements the <classname>MessageStore</classname> interface.
|
||||
</para>
|
||||
|
||||
<para>Details on how to configure a specific <emphasis>Message Store</emphasis> implementation and/or how to inject
|
||||
a <classname>MessageStore</classname> implementation into a specific buffering component are described
|
||||
throughout the manual (see the specific component, such as <emphasis>QueueChannel</emphasis>, <emphasis>Aggregator</emphasis>,
|
||||
<emphasis>Resequencer</emphasis> etc.), but here are a couple of samples to give you an idea:
|
||||
</para>
|
||||
|
||||
<para>
|
||||
QueueChannel
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="myQueueChannel">
|
||||
<int:queue message-store="refToMessageStore"/>
|
||||
<int:channel>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Aggregator
|
||||
<programlisting language="xml"><![CDATA[<int:aggregator . . . message-store="refToMessageStore"/>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
By default <emphasis>Messages</emphasis> are stored in-memory using <classname>org.springframework.integration.store.SimpleMessageStore</classname>,
|
||||
an implementation of <classname>MessageStore</classname>. That might be fine for development or simple low-volume environments where the potential loss
|
||||
of non-persistent messages is not a concern. However, the typical production application will need a more robust option, not only to mitigate the risk of
|
||||
message loss but also to avoid potential out-of-memory errors. Therefore, we also provide MessageStore implementations for a variety of data-stores.
|
||||
Below is a complete list of supported implementations:
|
||||
|
||||
<itemizedlist>
|
||||
<listitem><xref linkend="jdbc-message-store"/> - uses RDBMS to store Messages</listitem>
|
||||
<listitem><xref linkend="redis-message-store"/> - uses Redis key/value datastore to store Messages</listitem>
|
||||
<listitem><xref linkend="mongodb-message-store"/> - uses MongoDB document store to store Messages</listitem>
|
||||
<listitem><xref linkend="gemfire-message-store"/> - uses Gemfire distributed cache to store Messages</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<important>
|
||||
<para>However be aware of some limitations while using persistent implementations of the <classname>MessageStore</classname>.</para>
|
||||
<para>The Message data (payload and headers) is <emphasis>serialized</emphasis> and <emphasis>deserialized</emphasis>
|
||||
using different serialization strategies depending on the implementation of the <classname>MessageStore</classname>.
|
||||
For example, when using <classname>JdbcMessageStore</classname>, only <classname>Serializable</classname> data is persisted by default.
|
||||
In this case non-Serializable headers are removed before serialization occurs.
|
||||
Also be aware of the protocol specific headers that are injected by transport adapters (e.g., FTP, HTTP, JMS etc.).
|
||||
For example, <literal><http:inbound-channel-adapter/></literal> maps HTTP-headers into Message Headers and one of them is an
|
||||
<classname>ArrayList</classname> of non-Serializable <classname>org.springframework.http.MediaType</classname> instances.
|
||||
However you are able to inject your own implementation of the <classname>Serializer</classname> and/or
|
||||
<classname>Deserializer</classname> strategy interfaces into some <classname>MessageStore</classname> implementations
|
||||
(such as JdbcMessageStore) to change the behaviour of serialization and deserialization.
|
||||
</para>
|
||||
<para>
|
||||
Special attention must be paid to the headers that represent certain types of data.
|
||||
For example, if one of the headers contains an instance of some <emphasis>Spring Bean</emphasis>, upon deserialization you may end
|
||||
up with a different instance of that bean,
|
||||
which directly affects some of the implicit headers created by the framework (e.g., REPLY_CHANNEL or ERROR_CHANNEL).
|
||||
Currently they are not serializable, but even if they were the deserialized channel would not represent the expected instance.
|
||||
As a workaround we suggest to remove bean-ref headers via a <literal><header-filter/></literal>
|
||||
before sending a message to an endpoint backed by a persistent <classname>MessageStore</classname>.
|
||||
Also, we recommend using channel names instead of channel instances when setting those types of headers,
|
||||
thus allowing it to be resolved in real time by the <classname>ChannelResolver</classname>.
|
||||
</para>
|
||||
<para>
|
||||
Also avoid configuration of a message-flow like this:
|
||||
<emphasis>gateway -> queue-channel (backed by a persistent Message Store) -> service-activator</emphasis>
|
||||
That gateway creates a <emphasis>Temporary Reply Channel</emphasis> in the background, and it will be lost by the time the
|
||||
service-activator's poller reads from the queue, because it has been deserialized by another thread on the sending side.
|
||||
</para>
|
||||
<para>
|
||||
Nevertheless we are constantly thinking about potential improvements to the framework, such as a way to provide some
|
||||
robust default serialization strategy for messages in these cases.
|
||||
</para>
|
||||
</important>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
10
src/reference/docbook/message-transformation.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="messaging-transformation-chapter"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message Transformation</title>
|
||||
|
||||
<xi:include href="./transformer.xml"/>
|
||||
<xi:include href="./content-enrichment.xml"/>
|
||||
<xi:include href="./claim-check.xml"/>
|
||||
</chapter>
|
||||
218
src/reference/docbook/message.xml
Normal file
@@ -0,0 +1,218 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="message"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Message</title>
|
||||
<para>
|
||||
The Spring Integration <interfacename>Message</interfacename> is a generic container for data. Any object can
|
||||
be provided as the payload, and each <interfacename>Message</interfacename> also includes headers containing
|
||||
user-extensible properties as key-value pairs.
|
||||
</para>
|
||||
|
||||
<section id="message-interface">
|
||||
<title>The Message Interface</title>
|
||||
<para>Here is the definition of the <interfacename>Message</interfacename> interface:
|
||||
<programlisting language="java">public interface Message<T> {
|
||||
|
||||
T getPayload();
|
||||
|
||||
MessageHeaders getHeaders();
|
||||
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The <interfacename>Message</interfacename> is obviously a very important part of the API. By encapsulating the
|
||||
data in a generic wrapper, the messaging system can pass it around without any knowledge of the data's type. As
|
||||
an application evolves to support new types, or when the types themselves are modified and/or extended, the
|
||||
messaging system will not be affected by such changes. On the other hand, when some component in the messaging
|
||||
system <emphasis>does</emphasis> require access to information about the <interfacename>Message</interfacename>,
|
||||
such metadata can typically be stored to and retrieved from the metadata in the Message Headers.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="message-headers">
|
||||
<title>Message Headers</title>
|
||||
<para>
|
||||
Just as Spring Integration allows any Object to be used as the payload of a Message, it also supports any Object
|
||||
types as header values. In fact, the <classname>MessageHeaders</classname> class implements the
|
||||
<emphasis>java.util.Map</emphasis> interface:
|
||||
<programlisting language="java">public final class MessageHeaders implements Map<String, Object>, Serializable {
|
||||
...
|
||||
}</programlisting>
|
||||
<note>
|
||||
Even though the MessageHeaders implements Map, it is effectively a read-only implementation. Any attempt to
|
||||
<emphasis>put</emphasis> a value in the Map will result in an <classname>UnsupportedOperationException</classname>.
|
||||
The same applies for <emphasis>remove</emphasis> and <emphasis>clear</emphasis>. Since Messages may be passed to
|
||||
multiple consumers, the structure of the Map cannot be modified. Likewise, the Message's payload Object can not
|
||||
be <emphasis>set</emphasis> after the initial creation. However, the mutability of the header values themselves
|
||||
(or the payload Object) is intentionally left as a decision for the framework user.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
As an implementation of Map, the headers can obviously be retrieved by calling <methodname>get(..)</methodname>
|
||||
with the name of the header. Alternatively, you can provide the expected <emphasis>Class</emphasis> as an
|
||||
additional parameter. Even better, when retrieving one of the pre-defined values, convenient getters are
|
||||
available. Here is an example of each of these three options:
|
||||
<programlisting language="java"> Object someValue = message.getHeaders().get("someKey");
|
||||
|
||||
CustomerId customerId = message.getHeaders().get("customerId", CustomerId.class);
|
||||
|
||||
Long timestamp = message.getHeaders().getTimestamp();
|
||||
</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The following Message headers are pre-defined:
|
||||
<table id="message-headers-table">
|
||||
<title>Pre-defined Message Headers</title>
|
||||
<tgroup cols="2">
|
||||
<colspec align="left" />
|
||||
<thead>
|
||||
<row>
|
||||
<entry align="center">Header Name</entry>
|
||||
<entry align="center">Header Type</entry>
|
||||
</row>
|
||||
</thead>
|
||||
<tbody>
|
||||
<row>
|
||||
<entry>ID</entry>
|
||||
<entry>java.util.UUID</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>TIMESTAMP</entry>
|
||||
<entry>java.lang.Long</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>CORRELATION_ID</entry>
|
||||
<entry>java.lang.Object</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>REPLY_CHANNEL</entry>
|
||||
<entry>java.lang.Object (can be a String or MessageChannel)</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>ERROR_CHANNEL</entry>
|
||||
<entry>java.lang.Object (can be a String or MessageChannel)</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>SEQUENCE_NUMBER</entry>
|
||||
<entry>java.lang.Integer</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>SEQUENCE_SIZE</entry>
|
||||
<entry>java.lang.Integer</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>EXPIRATION_DATE</entry>
|
||||
<entry>java.lang.Long</entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>PRIORITY</entry>
|
||||
<entry>MessagePriority (an <emphasis>enum</emphasis>)</entry>
|
||||
</row>
|
||||
</tbody>
|
||||
</tgroup>
|
||||
</table>
|
||||
</para>
|
||||
<para>
|
||||
Many inbound and outbound adapter implementations will also provide and/or expect certain headers, and additional
|
||||
user-defined headers can also be configured.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="message-implementations">
|
||||
<title>Message Implementations</title>
|
||||
<para>
|
||||
The base implementation of the <interfacename>Message</interfacename> interface is
|
||||
<classname>GenericMessage<T></classname>, and it provides two constructors:
|
||||
<programlisting language="java">new GenericMessage<T>(T payload);
|
||||
|
||||
new GenericMessage<T>(T payload, Map<String, Object> headers)</programlisting>
|
||||
When a Message is created, a random unique id will be generated. The constructor that accepts a Map of headers
|
||||
will copy the provided headers to the newly created Message.
|
||||
</para>
|
||||
<para>
|
||||
There is also a convenient implementation of <interfacename>Message</interfacename> designed to communicate
|
||||
error conditions. This implementation takes <classname>Throwable</classname> object as its payload:
|
||||
<programlisting language="java">ErrorMessage message = new ErrorMessage(someThrowable);
|
||||
|
||||
Throwable t = message.getPayload();</programlisting>
|
||||
Notice that this implementation takes advantage of the fact that the <classname>GenericMessage</classname>
|
||||
base class is parameterized. Therefore, as shown in both examples, no casting is necessary when retrieving
|
||||
the Message payload Object.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="message-builder">
|
||||
<title>The MessageBuilder Helper Class</title>
|
||||
<para>
|
||||
You may notice that the Message interface defines retrieval methods for its payload and headers but no setters.
|
||||
The reason for this is that a Message cannot be modified after its initial creation. Therefore, when a Message
|
||||
instance is sent to multiple consumers (e.g. through a Publish Subscribe Channel), if one of those consumers
|
||||
needs to send a reply with a different payload type, it will need to create a new Message. As a result, the
|
||||
other consumers are not affected by those changes. Keep in mind, that multiple consumers may access the same
|
||||
payload instance or header value, and whether such an instance is itself immutable is a decision left to the
|
||||
developer. In other words, the contract for Messages is similar to that of an
|
||||
<emphasis>unmodifiable Collection</emphasis>, and the MessageHeaders' map further exemplifies that; even though
|
||||
the MessageHeaders class implements <interfacename>java.util.Map</interfacename>, any attempt to invoke a
|
||||
<emphasis>put</emphasis> operation (or 'remove' or 'clear') on the MessageHeaders will result in an
|
||||
<classname>UnsupportedOperationException</classname>.
|
||||
</para>
|
||||
<para>
|
||||
Rather than requiring the creation and population of a Map to pass into the GenericMessage constructor, Spring
|
||||
Integration does provide a far more convenient way to construct Messages: <classname>MessageBuilder</classname>.
|
||||
The MessageBuilder provides two factory methods for creating Messages from either an existing Message or with a
|
||||
payload Object. When building from an existing Message, the headers <emphasis>and payload</emphasis> of that
|
||||
Message will be copied to the new Message:
|
||||
<programlisting language="java">Message<String> message1 = MessageBuilder.withPayload("test")
|
||||
.setHeader("foo", "bar")
|
||||
.build();
|
||||
|
||||
Message<String> message2 = MessageBuilder.fromMessage(message1).build();
|
||||
|
||||
assertEquals("test", message2.getPayload());
|
||||
assertEquals("bar", message2.getHeaders().get("foo"));</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
If you need to create a Message with a new payload but still want to copy the
|
||||
headers from an existing Message, you can use one of the 'copy' methods.
|
||||
<programlisting language="java">Message<String> message3 = MessageBuilder.withPayload("test3")
|
||||
.copyHeaders(message1.getHeaders())
|
||||
.build();
|
||||
|
||||
Message<String> message4 = MessageBuilder.withPayload("test4")
|
||||
.setHeader("foo", 123)
|
||||
.copyHeadersIfAbsent(message1.getHeaders())
|
||||
.build();
|
||||
|
||||
assertEquals("bar", message3.getHeaders().get("foo"));
|
||||
assertEquals(123, message4.getHeaders().get("foo"));</programlisting>
|
||||
Notice that the <methodname>copyHeadersIfAbsent</methodname> does not overwrite existing values. Also, in the
|
||||
second example above, you can see how to set any user-defined header with <methodname>setHeader</methodname>.
|
||||
Finally, there are set methods available for the predefined headers as well as a non-destructive method for
|
||||
setting any header (MessageHeaders also defines constants for the pre-defined header names).
|
||||
<programlisting language="java">Message<Integer> importantMessage = MessageBuilder.withPayload(99)
|
||||
.setPriority(MessagePriority.HIGHEST)
|
||||
.build();
|
||||
|
||||
assertEquals(MessagePriority.HIGHEST, importantMessage.getHeaders().getPriority());
|
||||
|
||||
Message<Integer> anotherMessage = MessageBuilder.fromMessage(importantMessage)
|
||||
.setHeaderIfAbsent(MessageHeaders.PRIORITY, MessagePriority.LOW)
|
||||
.build();
|
||||
|
||||
assertEquals(MessagePriority.LOW, anotherMessage.getHeaders().getPriority());
|
||||
</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The <classname>MessagePriority</classname> is only considered when using a <classname>PriorityChannel</classname>
|
||||
(as described in the next chapter). It is defined as an <emphasis>enum</emphasis> with five possible values:
|
||||
<programlisting language="java">public enum MessagePriority {
|
||||
HIGHEST,
|
||||
HIGH,
|
||||
NORMAL,
|
||||
LOW,
|
||||
LOWEST
|
||||
}</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
11
src/reference/docbook/messaging-channels.xml
Normal file
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="messaging-channels-section"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Messaging Channels</title>
|
||||
|
||||
<xi:include href="./channel.xml"/>
|
||||
<xi:include href="./channel-adapter.xml"/>
|
||||
<xi:include href="./bridge.xml"/>
|
||||
|
||||
</chapter>
|
||||
14
src/reference/docbook/messaging-endpoints.xml
Normal file
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="messaging-endpoints-chapter"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Messaging Endpoints</title>
|
||||
|
||||
<xi:include href="./endpoint.xml"/>
|
||||
<xi:include href="./gateway.xml"/>
|
||||
<xi:include href="./service-activator.xml"/>
|
||||
<xi:include href="./delayer.xml"/>
|
||||
<xi:include href="./scripting.xml"/>
|
||||
<xi:include href="./groovy.xml"/>
|
||||
|
||||
</chapter>
|
||||
116
src/reference/docbook/mongodb.xml
Normal file
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="mongodb"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
|
||||
<title>MongoDb Support</title>
|
||||
|
||||
<para>
|
||||
As of version 2.1 Spring Integration introduces support for <ulink url="http://www.mongodb.org/">MongoDB</ulink>:
|
||||
a <emphasis>"high-performance, open source, document-oriented database"</emphasis>.
|
||||
This support comes in the form of a MongoDB-based MessageStore.
|
||||
</para>
|
||||
|
||||
<section id="mongodb-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
To download, install, and run MongoDB please refer to the <ulink url="http://www.mongodb.org/downloads">MongoDB documentation</ulink>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="mongodb-connection">
|
||||
<title>Connecting to MongoDb</title>
|
||||
|
||||
<para>To begin interacting with MongoDB you first need to connect to it. Spring Integration builds on the support provided by another
|
||||
Spring project, <ulink url="http://www.springsource.org/spring-data/mongodb">Spring Data MongoDB</ulink>, which provides a factory
|
||||
class called <classname>MongoDbFactory</classname> that simplifies integration with the MongoDB Client API.</para>
|
||||
|
||||
<para><emphasis>MongoDbFactory</emphasis> </para>
|
||||
|
||||
<para>
|
||||
To connect to MongoDB you can use an implementation of the <classname>MongoDbFactory</classname> interface:
|
||||
|
||||
<programlisting lang="java"><![CDATA[public interface MongoDbFactory {
|
||||
|
||||
/**
|
||||
* Creates a default {@link DB} instance.
|
||||
*
|
||||
* @return the DB instance
|
||||
* @throws DataAccessException
|
||||
*/
|
||||
DB getDb() throws DataAccessException;
|
||||
|
||||
/**
|
||||
* Creates a {@link DB} instance to access the database with the given name.
|
||||
*
|
||||
* @param dbName must not be {@literal null} or empty.
|
||||
*
|
||||
* @return the DB instance
|
||||
* @throws DataAccessException
|
||||
*/
|
||||
DB getDb(String dbName) throws DataAccessException;
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>The example below shows <classname>SimpleMongoDbFactory</classname>, the out-of-the-box implementation:</para>
|
||||
|
||||
<para>In Java:
|
||||
<programlisting lang="java"><![CDATA[MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new Mongo(), "test");]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>Or in Spring's XML configuration:
|
||||
<programlisting lang="xml"><![CDATA[<bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
|
||||
<constructor-arg>
|
||||
<bean class="com.mongodb.Mongo"/>
|
||||
</constructor-arg>
|
||||
<constructor-arg value="test"/>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
As you can see <classname>SimpleMongoDbFactory</classname> takes two arguments: 1) a <classname>Mongo</classname> instance and
|
||||
2) a String specifying the name of the database. If you need to configure properties such as <code>host</code>, <code>port</code>, etc,
|
||||
you can pass those using one of the constructors provided by the underlying <classname>Mongo</classname> class.
|
||||
For more information on how to configure MongoDB, please refer to the
|
||||
<ulink url="http://static.springsource.org/spring-data/data-document/docs/current/reference/html/">Spring-Data-Document</ulink> reference.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="mongodb-message-store">
|
||||
<title>MongoDB Message Store</title>
|
||||
|
||||
<para>
|
||||
As described in EIP, a <ulink url="http://www.eaipatterns.com/MessageStore.html">Message Store</ulink> allows you to persist Messages.
|
||||
This can be very useful when dealing with components that have a capability to buffer messages
|
||||
(<emphasis>QueueChannel, Aggregator, Resequencer</emphasis>, etc.) if reliability is a concern.
|
||||
In Spring Integration, the MessageStore strategy also provides the foundation for the
|
||||
<ulink url="http://www.eaipatterns.com/StoreInLibrary.html">ClaimCheck</ulink> pattern, which is described in EIP as well.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration's MongoDB module provides the <classname>MongoDbMessageStore</classname> which is an implementation of both
|
||||
the <classname>MessageStore</classname> strategy (mainly used by the <emphasis>QueueChannel</emphasis> and <emphasis>ClaimCheck</emphasis>
|
||||
patterns) and the <classname>MessageGroupStore</classname> strategy (mainly used by the <emphasis>Aggregator</emphasis> and
|
||||
<emphasis>Resequencer</emphasis> patterns).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<programlisting lang="xml"><![CDATA[<bean id="mongoDbMessageStore" class="org.springframework.integration.mongodb.store.MongoDbMessageStore">
|
||||
<constructor-arg ref="mongoDbFactory"/>
|
||||
</bean>
|
||||
|
||||
<int:channel id="somePersistentQueueChannel">
|
||||
<int:queue message-store="mongoDbMessageStore"/>
|
||||
<int:channel>
|
||||
|
||||
<int:aggregator input-channel="inputChannel" output-channel="outputChannel"
|
||||
message-store="mongoDbMessageStore"/>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Above is a sample <classname>MongoDbMessageStore</classname> configuration that shows its usage by a <emphasis>QueueChannel</emphasis>
|
||||
and an <emphasis>Aggregator</emphasis>. As you can see it is a simple bean configuration, and it expects a
|
||||
<classname>MongoDbFactory</classname> as a constructor argument.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
321
src/reference/docbook/overview.xml
Normal file
@@ -0,0 +1,321 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="overview"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Spring Integration Overview</title>
|
||||
|
||||
<section id="overview-background">
|
||||
<title>Background</title>
|
||||
<para>
|
||||
One of the key themes of the Spring Framework is <emphasis>inversion of control</emphasis>. In its broadest
|
||||
sense, this means that the framework handles responsibilities on behalf of the components that are managed within
|
||||
its context. The components themselves are simplified since they are relieved of those responsibilities. For
|
||||
example, <emphasis>dependency injection</emphasis> relieves the components of the responsibility of locating or
|
||||
creating their dependencies. Likewise, <emphasis>aspect-oriented programming</emphasis> relieves business
|
||||
components of generic cross-cutting concerns by modularizing them into reusable aspects. In each case, the end
|
||||
result is a system that is easier to test, understand, maintain, and extend.
|
||||
</para>
|
||||
<para>
|
||||
Furthermore, the Spring framework and portfolio provide a comprehensive programming model for building
|
||||
enterprise applications. Developers benefit from the consistency of this model and especially the fact that it is
|
||||
based upon well-established best practices such as programming to interfaces and favoring composition over
|
||||
inheritance. Spring's simplified abstractions and powerful support libraries boost developer productivity while
|
||||
simultaneously increasing the level of testability and portability.
|
||||
</para>
|
||||
<para>
|
||||
Spring Integration is motivated by these same goals and principles. It
|
||||
extends the Spring programming model into the messaging domain and builds upon Spring's existing enterprise
|
||||
integration support to provide an even higher level of abstraction. It supports message-driven architectures
|
||||
where inversion of control applies to runtime concerns, such as <emphasis>when</emphasis> certain business logic
|
||||
should execute and <emphasis>where</emphasis> the response should be sent. It supports routing and transformation
|
||||
of messages so that different transports and different data formats can be integrated without impacting
|
||||
testability. In other words, the messaging and integration concerns are handled by the framework, so business
|
||||
components are further isolated from the infrastructure and developers are relieved of complex integration
|
||||
responsibilities.
|
||||
</para>
|
||||
<para>
|
||||
As an extension of the Spring programming model, Spring Integration provides a wide variety of configuration
|
||||
options including annotations, XML with namespace support, XML with generic "bean" elements, and of course direct
|
||||
usage of the underlying API. That API is based upon well-defined strategy interfaces and non-invasive, delegating
|
||||
adapters. Spring Integration's design is inspired by the recognition of a strong affinity between common patterns
|
||||
within Spring and the well-known <ulink url="http://www.eaipatterns.com">Enterprise Integration Patterns</ulink>
|
||||
as described in the book of the same name by Gregor Hohpe and Bobby Woolf (Addison Wesley, 2004). Developers who
|
||||
have read that book should be immediately comfortable with the Spring Integration concepts and terminology.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-goalsandprinciples">
|
||||
<title>Goals and Principles</title>
|
||||
<para>Spring Integration is motivated by the following goals:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>Provide a simple model for implementing complex enterprise integration solutions.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Facilitate asynchronous, message-driven behavior within a Spring-based application.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Promote intuitive, incremental adoption for existing Spring users.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>Spring Integration is guided by the following principles:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>Components should be <emphasis>loosely coupled</emphasis> for modularity and testability.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>The framework should enforce <emphasis>separation of concerns</emphasis> between business logic and
|
||||
integration logic.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Extension points should be abstract in nature but within well-defined boundaries to promote
|
||||
<emphasis>reuse</emphasis> and <emphasis>portability</emphasis>.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-components">
|
||||
<title>Main Components</title>
|
||||
<para>
|
||||
From the <emphasis>vertical</emphasis> perspective, a layered architecture facilitates separation of concerns,
|
||||
and interface-based contracts between layers promote loose coupling. Spring-based applications are typically
|
||||
designed this way, and the Spring framework and portfolio provide a strong foundation for following this best
|
||||
practice for the full-stack of an enterprise application. Message-driven architectures add a
|
||||
<emphasis>horizontal</emphasis> perspective, yet these same goals are still relevant. Just as "layered
|
||||
architecture" is an extremely generic and abstract paradigm, messaging systems typically follow the similarly
|
||||
abstract "pipes-and-filters" model. The "filters" represent any component that is capable of producing and/or
|
||||
consuming messages, and the "pipes" transport the messages between filters so that the components themselves
|
||||
remain loosely-coupled. It is important to note that these two high-level paradigms are not mutually exclusive.
|
||||
The underlying messaging infrastructure that supports the "pipes" should still be encapsulated in a layer whose
|
||||
contracts are defined as interfaces. Likewise, the "filters" themselves would typically be managed within a layer
|
||||
that is logically above the application's service layer, interacting with those services through interfaces much
|
||||
in the same way that a web-tier would.
|
||||
</para>
|
||||
|
||||
<section id="overview-components-message">
|
||||
<title>Message</title>
|
||||
<para>
|
||||
In Spring Integration, a Message is a generic wrapper for any Java object combined with metadata used by the
|
||||
framework while handling that object. It consists of a payload and headers. The payload can be of any type and
|
||||
the headers hold commonly required information such as id, timestamp, correlation id, and return address. Headers
|
||||
are also used for passing values to and from connected transports. For example, when creating a Message from a
|
||||
received File, the file name may be stored in a header to be accessed by downstream components. Likewise, if a
|
||||
Message's content is ultimately going to be sent by an outbound Mail adapter, the various properties (to, from,
|
||||
cc, subject, etc.) may be configured as Message header values by an upstream component. Developers can also
|
||||
store any arbitrary key-value pairs in the headers.
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/message.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/message.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-components-channel">
|
||||
<title>Message Channel</title>
|
||||
<para>
|
||||
A Message Channel represents the "pipe" of a pipes-and-filters architecture. Producers send Messages to
|
||||
a channel, and consumers receive Messages from a channel. The Message Channel therefore decouples the
|
||||
messaging components, and also provides a convenient point for interception and monitoring of Messages.
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/channel.jpg" format="JPG" align="center" scalefit="1" width="100%" contentdepth="100%" />
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/channel.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
A Message Channel may follow either Point-to-Point or Publish/Subscribe semantics. With a Point-to-Point
|
||||
channel, at most one consumer can receive each Message sent to the channel. Publish/Subscribe channels, on the
|
||||
other hand, will attempt to broadcast each Message to all of its subscribers. Spring Integration supports
|
||||
both of these.
|
||||
</para>
|
||||
<para>
|
||||
Whereas "Point-to-Point" and "Publish/Subscribe" define the two options for <emphasis>how many</emphasis>
|
||||
consumers will ultimately receive each Message, there is another important consideration: should the channel
|
||||
buffer messages? In Spring Integration, <emphasis>Pollable Channels</emphasis> are capable of buffering
|
||||
Messages within a queue. The advantage of buffering is that it allows for throttling the inbound Messages and
|
||||
thereby prevents overloading a consumer. However, as the name suggests, this also adds some complexity, since a
|
||||
consumer can only receive the Messages from such a channel if a <emphasis>poller</emphasis> is configured. On
|
||||
the other hand, a consumer connected to a <emphasis>Subscribable Channel</emphasis> is simply Message-driven.
|
||||
The variety of channel implementations available in Spring Integration will be discussed in detail in
|
||||
<xref linkend="channel-implementations"/>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-components-endpoint">
|
||||
<title>Message Endpoint</title>
|
||||
<para>
|
||||
One of the primary goals of Spring Integration is to simplify the development of enterprise integration
|
||||
solutions through <emphasis>inversion of control</emphasis>. This means that you should not have to implement
|
||||
consumers and producers directly, and you should not even have to build Messages and invoke send or receive
|
||||
operations on a Message Channel. Instead, you should be able to focus on your specific domain model with an
|
||||
implementation based on plain Objects. Then, by providing declarative configuration, you can "connect"
|
||||
your domain-specific code to the messaging infrastructure provided by Spring Integration. The components
|
||||
responsible for these connections are Message Endpoints. This does not mean that you will necessarily connect
|
||||
your existing application code directly. Any real-world enterprise integration solution will require some
|
||||
amount of code focused upon integration concerns such as <emphasis>routing</emphasis> and
|
||||
<emphasis>transformation</emphasis>. The important thing is to achieve separation of concerns between such
|
||||
integration logic and business logic. In other words, as with the Model-View-Controller paradigm for web
|
||||
applications, the goal should be to provide a thin but dedicated layer that translates inbound requests into
|
||||
service layer invocations, and then translates service layer return values into outbound replies. The next
|
||||
section will provide an overview of the Message Endpoint types that handle these responsibilities, and in
|
||||
upcoming chapters, you will see how Spring Integration's declarative configuration options provide a
|
||||
non-invasive way to use each of these.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="overview-endpoints">
|
||||
<title>Message Endpoints</title>
|
||||
<para>
|
||||
A Message Endpoint represents the "filter" of a pipes-and-filters architecture. As mentioned above, the
|
||||
endpoint's primary role is to connect application code to the messaging framework and to do so in a non-invasive
|
||||
manner. In other words, the application code should ideally have no awareness of the Message objects or the
|
||||
Message Channels. This is similar to the role of a Controller in the MVC paradigm. Just as a Controller handles
|
||||
HTTP requests, the Message Endpoint handles Messages. Just as Controllers are mapped to URL patterns, Message
|
||||
Endpoints are mapped to Message Channels. The goal is the same in both cases: isolate application code from the
|
||||
infrastructure. These concepts are discussed at length along with all of the patterns that follow in the
|
||||
<ulink url="http://www.eaipatterns.com">Enterprise Integration Patterns</ulink> book. Here, we provide only a
|
||||
high-level description of the main endpoint types supported by Spring Integration and their roles. The chapters
|
||||
that follow will elaborate and provide sample code as well as configuration examples.
|
||||
</para>
|
||||
|
||||
<section id="overview-endpoints-transformer">
|
||||
<title>Transformer</title>
|
||||
<para>
|
||||
A Message Transformer is responsible for converting a Message's content or structure and returning the modified
|
||||
Message. Probably the most common type of transformer is one that converts the payload of the Message from one
|
||||
format to another (e.g. from XML Document to java.lang.String). Similarly, a transformer may be used to add,
|
||||
remove, or modify the Message's header values.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-endpoints-filter">
|
||||
<title>Filter</title>
|
||||
<para>
|
||||
A Message Filter determines whether a Message should be passed to an output channel at all. This simply
|
||||
requires a boolean test method that may check for a particular payload content type, a property value, the
|
||||
presence of a header, etc. If the Message is accepted, it is sent to the output channel, but if not it will be
|
||||
dropped (or for a more severe implementation, an Exception could be thrown). Message Filters are often used in
|
||||
conjunction with a Publish Subscribe channel, where multiple consumers may receive the same Message and use the
|
||||
filter to narrow down the set of Messages to be processed based on some criteria.
|
||||
<note>
|
||||
Be careful not to confuse the generic use of "filter" within the Pipes-and-Filters architectural pattern with
|
||||
this specific endpoint type that selectively narrows down the Messages flowing between two channels. The
|
||||
Pipes-and-Filters concept of "filter" matches more closely with Spring Integration's Message Endpoint: any
|
||||
component that can be connected to Message Channel(s) in order to send and/or receive Messages.
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-endpoints-router">
|
||||
<title>Router</title>
|
||||
<para>
|
||||
A Message Router is responsible for deciding what channel or channels should receive the Message next (if any).
|
||||
Typically the decision is based upon the Message's content and/or metadata available in the Message Headers.
|
||||
A Message Router is often used as a dynamic alternative to a statically configured output channel on
|
||||
a Service Activator or other endpoint capable of sending reply Messages. Likewise, a Message Router provides a
|
||||
proactive alternative to the reactive Message Filters used by multiple subscribers as described above.
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/router.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/router.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-endpoints-splitter">
|
||||
<title>Splitter</title>
|
||||
<para>
|
||||
A Splitter is another type of Message Endpoint whose responsibility is to accept a Message from its input
|
||||
channel, split that Message into multiple Messages, and then send each of those to its output channel. This
|
||||
is typically used for dividing a "composite" payload object into a group of Messages containing the
|
||||
sub-divided payloads.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-endpoints-aggregator">
|
||||
<title>Aggregator</title>
|
||||
<para>
|
||||
Basically a mirror-image of the Splitter, the Aggregator is a type of Message Endpoint that receives multiple
|
||||
Messages and combines them into a single Message. In fact, Aggregators are often downstream consumers in a
|
||||
pipeline that includes a Splitter. Technically, the Aggregator is more complex than a Splitter, because it
|
||||
is required to maintain state (the Messages to-be-aggregated), to decide when the complete group of Messages
|
||||
is available, and to timeout if necessary. Furthermore, in case of a timeout, the Aggregator needs to know
|
||||
whether to send the partial results or to discard them to a separate channel. Spring Integration provides
|
||||
a <interfacename>CompletionStrategy</interfacename> as well as configurable settings for timeout, whether
|
||||
to send partial results upon timeout, and the discard channel.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-endpoints-service-activator">
|
||||
<title>Service Activator</title>
|
||||
<para>
|
||||
A Service Activator is a generic endpoint for connecting a service instance to the messaging system. The
|
||||
input Message Channel must be configured, and if the service method to be invoked is capable of returning a
|
||||
value, an output Message Channel may also be provided.
|
||||
<note>
|
||||
The output channel is optional, since each Message may also provide its own 'Return Address' header. This
|
||||
same rule applies for all consumer endpoints.
|
||||
</note>
|
||||
The Service Activator invokes an operation on some service object to process the request Message, extracting
|
||||
the request Message's payload and converting if necessary (if the method does not expect a Message-typed
|
||||
parameter). Whenever the service object's method returns a value, that return value will likewise be converted
|
||||
to a reply Message if necessary (if it's not already a Message). That reply Message is sent to the output
|
||||
channel. If no output channel has been configured, then the reply will be sent to the channel specified in the
|
||||
Message's "return address" if available.
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/handler-endpoint.jpg" format="JPG" align="center" scalefit="1" width="100%"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/handler-endpoint.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<caption>
|
||||
A request-reply "Service Activator" endpoint connects a target object's method to input and output
|
||||
Message Channels.
|
||||
</caption>
|
||||
</mediaobject>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="overview-endpoints-channeladapter">
|
||||
<title>Channel Adapter</title>
|
||||
<para>
|
||||
A Channel Adapter is an endpoint that connects a Message Channel to some other system or transport. Channel
|
||||
Adapters may be either inbound or outbound. Typically, the Channel Adapter will do some mapping between the
|
||||
Message and whatever object or resource is received-from or sent-to the other system (File, HTTP Request, JMS
|
||||
Message, etc). Depending on the transport, the Channel Adapter may also populate or extract Message header
|
||||
values. Spring Integration provides a number of Channel Adapters, and they will be described in upcoming
|
||||
chapters.
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/source-endpoint.jpg" format="JPG" align="center" scalefit="1" width="100%"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/source-endpoint.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<caption>An inbound "Channel Adapter" endpoint connects a source system to a MessageChannel.</caption>
|
||||
</mediaobject>
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/target-endpoint.jpg" format="JPG" align="center" scalefit="1" width="100%"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/target-endpoint.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<caption>An outbound "Channel Adapter" endpoint connects a MessageChannel to a target system.</caption>
|
||||
</mediaobject>
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
56
src/reference/docbook/preface.xml
Normal file
@@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<preface xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" version="5.0" xml:id="preface">
|
||||
<title>Preface</title>
|
||||
|
||||
<section id="code-conventions">
|
||||
<title>Code Conventions</title>
|
||||
<para>
|
||||
The Spring Framework 2.0 introduced support for namespaces, which
|
||||
simplifies the Xml configuration of the application context, and consequently
|
||||
Spring Integration provides broad namespace support. This reference guide
|
||||
applies the following conventions for all code examples that use namespace
|
||||
support:
|
||||
</para>
|
||||
<para>
|
||||
The <emphasis role="bold">int</emphasis> namespace prefix will be used for
|
||||
Spring Integration's core namespace support. Each Spring Integration adapter
|
||||
type (module) will provide its own namespace, which is configured using the
|
||||
following convention:
|
||||
</para>
|
||||
<para>
|
||||
<emphasis role="bold">int-</emphasis> followed by the name of the module, e.g.
|
||||
<emphasis role="bold">int-twitter</emphasis>,
|
||||
<emphasis role="bold">int-stream</emphasis>, …
|
||||
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:int="http://www.springframework.org/schema/integration"
|
||||
xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
|
||||
xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd
|
||||
http://www.springframework.org/schema/integration/twitter
|
||||
http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd
|
||||
http://www.springframework.org/schema/integration/stream
|
||||
http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd">
|
||||
…
|
||||
</beans>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
For a detailed explanation regarding Spring Integration's namespace support
|
||||
see <emphasis><xref linkend="configuration-namespace"/></emphasis>.
|
||||
<note>
|
||||
Please note that the namespace prefix can be freely chosen. You may
|
||||
even choose not to use any namespace prefixes at all. Therefore,
|
||||
apply the convention that suits your application needs best. Be aware,
|
||||
though, that SpringSource Tool Suite™ (STS) uses the same namespace
|
||||
conventions for Spring Integration as used in this reference guide.
|
||||
</note>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
</preface>
|
||||
224
src/reference/docbook/redis.xml
Normal file
@@ -0,0 +1,224 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="redis"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
|
||||
<title>Redis Support</title>
|
||||
|
||||
<para>
|
||||
Since version 2.1 Spring Integration introduces support for <ulink url="http://redis.io/">Redis</ulink>:
|
||||
<emphasis>"an open source advanced key-value store". </emphasis>
|
||||
This support comes in the form of a Redis-based MessageStore as well as Publish-Subscribe Messaging adapters that
|
||||
are supported by Redis via its <ulink url="http://redis.io/topics/pubsub">PUBLISH, SUBSCRIBE and UNSUBSCRIBE</ulink> commands.
|
||||
</para>
|
||||
|
||||
<section id="redis-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
To download, install and run Redis please refer to the <ulink url="http://redis.io/download">Redis documentation</ulink>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="redis-connection">
|
||||
<title>Connecting to Redis</title>
|
||||
|
||||
<para>To begin interacting with Redis you first need to connect to it. Spring Integration uses support provided by another Spring project,
|
||||
<ulink url="https://github.com/SpringSource/spring-data-redis">Spring Data Redis</ulink>, which provides typical Spring constructs:
|
||||
<classname>ConnectionFactory</classname> and <classname>Template</classname>. Those abstractions
|
||||
simplify integration with several Redis-client Java APIs. Currently Spring-Data-Redis supports
|
||||
<ulink url="https://github.com/xetorthio/jedis">jedis</ulink>, <ulink url="http://code.google.com/p/jredis/">jredis</ulink> and <ulink url="https://github.com/e-mzungu/rjc">rjc</ulink></para>
|
||||
|
||||
<para><emphasis>RedisConnectionFactory</emphasis> </para>
|
||||
|
||||
<para>
|
||||
To connect to Redis you would use one of the implementations of the <classname>RedisConnectionFactory</classname> interface:
|
||||
|
||||
<programlisting lang="java"><![CDATA[public interface RedisConnectionFactory extends PersistenceExceptionTranslator {
|
||||
|
||||
/**
|
||||
* Provides a suitable connection for interacting with Redis.
|
||||
*
|
||||
* @return connection for interacting with Redis.
|
||||
*/
|
||||
RedisConnection getConnection();
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>The example below shows how to create a <classname>JedisConnectionFactory</classname>.</para>
|
||||
|
||||
<para>In Java:
|
||||
<programlisting lang="java"><![CDATA[JedisConnectionFactory jcf = new JedisConnectionFactory();
|
||||
jcf.afterPropertiesSet();]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>Or in Spring's XML configuration:
|
||||
<programlisting lang="xml"><![CDATA[<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
|
||||
<property name="port" value="7379" />
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The implementations of RedisConnectionFactory provide a set of properties such as port and host that can be set if needed.
|
||||
Once an instance of RedisConnectionFactory is created, you can create an instance of RedisTemplate and inject it with the RedisConnectionFactory.
|
||||
</para>
|
||||
|
||||
<para><emphasis>RedisTemplate</emphasis> </para>
|
||||
|
||||
<para>
|
||||
As with other template classes in Spring (e.g., <classname>JdbcTemplate</classname>, <classname>JmsTemplate</classname>)
|
||||
<classname>RedisTemplate</classname> is a helper class that simplifies Redis data access code.
|
||||
For more information about <classname>RedisTemplate</classname> and its variations (e.g., <classname>StringRedisTemplate</classname>)
|
||||
please refer to the <ulink url="http://static.springsource.org/spring-data/data-redis/docs/current/reference/">Spring-Data-Redis documentation</ulink>
|
||||
</para>
|
||||
|
||||
<para>The code below shows how to create an instance of <classname>RedisTemplate</classname>:</para>
|
||||
|
||||
<para>In Java:
|
||||
<programlisting lang="java"><![CDATA[RedisTemplate rt = new RedisTemplate<String, Object>();
|
||||
rt.setConnectionFactory(redisConnectionFactory);]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>Or in Spring's XML configuration::
|
||||
<programlisting lang="xml"><![CDATA[<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
|
||||
<property name="connectionFactory" ref="redisConnectionFactory"/>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="redis-messages">
|
||||
<title>Messaging with Redis</title>
|
||||
|
||||
<para>
|
||||
As mentioned in the introduction Redis provides support for Publish-Subscribe messaging via its PUBLISH, SUBSCRIBE and UNSUBSCRIBE
|
||||
commands. As with JMS and AMQP, Spring Integration provides Message Channels and adapters for sending and receiving messages via Redis.
|
||||
</para>
|
||||
|
||||
<section id="redis-pub-sub-channel">
|
||||
<title>Redis Publish/Subscribe channel</title>
|
||||
|
||||
<para>
|
||||
Similar to the JMS there are cases where both the producer and consumer are intended to be part of the same application, running
|
||||
within the same process. This could be accomplished by using a pair of inbound and outbound Channel Adapters,
|
||||
however just like with Spring Integration's JMS support, there is a simpler approach to address this use case.
|
||||
<programlisting lang="xml"><![CDATA[<int-redis:publish-subscribe-channel id="redisChannel" topic-name="si.test.topic"/>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The publish-subscribe-channel (above) will behave much like a normal <code><publish-subscribe-channel/></code> element from the
|
||||
main Spring Integration namespace. It can be referenced by both <code>input-channel</code> and <code>output-channel</code> attributes of
|
||||
any endpoint. The difference is that this channel is backed by a Redis topic name - a String value specified by the <code>topic-name</code>
|
||||
attribute. However unlike JMS this topic doesn't have to be created in advance or even auto-created by Redis. In Redis topics are simple
|
||||
String values that play the role of an address, and all the producer and consumer need to do to communicate is use the same String value
|
||||
as their topic name. A simple subscription to this channel means that asynchronous pub-sub messaging is possible between the producing and
|
||||
consuming endpoints, but unlike the asynchronous Message Channels created by adding a <code> <queue/></code> sub-element within
|
||||
a simple Spring Integration <code><channel/></code> element, the Messages are not just stored in an in-memory queue. Instead those
|
||||
Messages are passed through Redis allowing you to rely on its support for persistence and clustering as well as its interoperability with
|
||||
other non-java platforms.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="redis-inbound-channel-adapter">
|
||||
<title>Redis Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The Redis-based Inbound Channel Adapter adapts incoming Redis messages into Spring Integration Messages in the same way as other
|
||||
inbound adapters. It receives platform-specific messages (Redis in this case) and converts them to Spring Integration Messages using
|
||||
a <classname>MessageConverter</classname> strategy.
|
||||
|
||||
<programlisting lang="xml"><![CDATA[<int-redis:inbound-channel-adapter id="redisAdapter"
|
||||
topics="foo, bar"
|
||||
channel="receiveChannel"
|
||||
error-channel="testErrorChannel"
|
||||
message-converter="testConverter" />
|
||||
|
||||
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
|
||||
<property name="port" value="7379" />
|
||||
</bean>
|
||||
|
||||
<bean id="testConverter" class="foo.bar.SampleMessageConverter" />]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Above is a simple but complete configuration of a Redis Inbound Channel Adapter. Note that the above configuration relies on the
|
||||
familiar Spring paradigm of auto-discovering certain beans. In this case the <code>redisConnectionFactory</code> is implicitly
|
||||
injected into the adapter. You can of course specify it explicitly using the <code>connection-factory</code> attribute instead.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Also, note that the above configuration injects the adapter with a custom <code>MessageConverter</code>.
|
||||
The approach is similar to JMS where <code>MessageConverters</code> are used to convert between
|
||||
Redis Messages and the Spring Integration Message payloads. The default is a <code>SimpleMessageConverter</code>.
|
||||
</para>
|
||||
|
||||
<para>Inbound adapters can subscribe to multiple topic names hence the comma-delimited set of values in the
|
||||
<code>topics</code> attribute.</para>
|
||||
</section>
|
||||
|
||||
<section id="redis-outbound-channel-adapter">
|
||||
<title>Redis Outbound Channel Adapter</title>
|
||||
<para>
|
||||
The Redis-based Outbound Channel Adapter adapts outgoing Spring Integration messages into Redis messages in the same way as
|
||||
other outbound adapters. It receives Spring Integration messages and converts them to platform-specific messages (Redis in this case)
|
||||
using a <classname>MessageConverter</classname> strategy.
|
||||
|
||||
<programlisting lang="xml"><![CDATA[<int-redis:outbound-channel-adapter id="outboundAdapter"
|
||||
channel="sendChannel"
|
||||
topic="foo"
|
||||
message-converter="testConverter"/>
|
||||
|
||||
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
|
||||
<property name="port" value="7379"/>
|
||||
</bean>
|
||||
|
||||
<bean id="testConverter" class="foo.bar.SampleMessageConverter" />]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
As you can see the configuration is similar to the Redis Inbound Channel Adapter. The adapter is implicitly injected with
|
||||
a <classname>RedisConnectionFactory</classname> which was defined with '<code>redisConnectionFactory</code>' as its bean name.
|
||||
This example also includes the optional, custom <classname>MessageConverter</classname> (the '<code>testConverter</code>' bean).
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="redis-message-store">
|
||||
<title>Redis Message Store</title>
|
||||
|
||||
<para>
|
||||
As described in EIP, a <ulink url="http://www.eaipatterns.com/MessageStore.html">Message Store</ulink> allows you to persist Messages.
|
||||
This can be very useful when dealing with components that have a capability to buffer messages
|
||||
(<emphasis>QueueChannel, Aggregator, Resequencer</emphasis>, etc.) if reliability is a concern.
|
||||
In Spring Integration, the MessageStore strategy also provides the foundation for the
|
||||
<ulink url="http://www.eaipatterns.com/StoreInLibrary.html">ClaimCheck</ulink> pattern, which is described in EIP as well.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration's Redis module provides the <classname>RedisMessageStore</classname> which is an implementation of both the
|
||||
the <classname>MessageStore</classname> strategy (mainly used by the <emphasis>QueueChannel</emphasis> and <emphasis>ClaimCheck</emphasis>
|
||||
patterns) and the <classname>MessageGroupStore</classname> strategy (mainly used by the <emphasis>Aggregator</emphasis> and
|
||||
<emphasis>Resequencer</emphasis> patterns).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<programlisting lang="xml"><![CDATA[<bean id="redisMessageStore" class="org.springframework.integration.redis.store.RedisMessageStore">
|
||||
<constructor-arg ref="redisConnectionFactory"/>
|
||||
</bean>
|
||||
|
||||
<int:channel id="somePersistentQueueChannel">
|
||||
<int:queue message-store="redisMessageStore"/>
|
||||
<int:channel>
|
||||
|
||||
<int:aggregator input-channel="inputChannel" output-channel="outputChannel"
|
||||
message-store="redisMessageStore"/>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Above is a sample <classname>RedisMessageStore</classname> configuration that shows its usage by a <emphasis>QueueChannel</emphasis>
|
||||
and an <emphasis>Aggregator</emphasis>. As you can see it is a simple bean configuration, and it expects a
|
||||
<classname>RedisConnectionFactory</classname> as a constructor argument.
|
||||
</para>
|
||||
|
||||
<para>By default the <classname>RedisMessageStore</classname> will use Java serialization to serialize the Message.
|
||||
However if you want to use a different serialization technique (e.g., JSON), you can provide your own serializer via
|
||||
the <code>valueSerializer</code> property of the <classname>RedisMessageStore</classname>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
126
src/reference/docbook/resequencer.xml
Normal file
@@ -0,0 +1,126 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="resequencer"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Resequencer</title>
|
||||
|
||||
<section>
|
||||
<title>Introduction</title>
|
||||
|
||||
<para>Related to the Aggregator, albeit different from a functional
|
||||
standpoint, is the Resequencer.</para>
|
||||
</section>
|
||||
|
||||
<section id="resequencer-functionality">
|
||||
<title>Functionality</title>
|
||||
|
||||
<para>The Resequencer works in a similar way to the Aggregator, in the
|
||||
sense that it uses the CORRELATION_ID to store messages in groups, the
|
||||
difference being that the Resequencer does not process the messages in any
|
||||
way. It simply releases them in the order of their SEQUENCE_NUMBER header
|
||||
values.</para>
|
||||
|
||||
<para>With respect to that, the user might opt to release all messages at
|
||||
once (after the whole sequence, according to the SEQUENCE_SIZE, has been
|
||||
released), or as soon as a valid sequence is available.</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Configuring a Resequencer</title>
|
||||
|
||||
<para>Configuring a resequencer requires only including the appropriate
|
||||
element in XML.</para>
|
||||
|
||||
<para>A sample resequencer configuration is shown below.</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:channel id="inputChannel"/>
|
||||
|
||||
<int:channel id="outputChannel"/>
|
||||
|
||||
<int:resequencer id="completelyDefinedResequencer" ]]><co id="resxml1-co"
|
||||
linkends="resxml1" /><![CDATA[
|
||||
input-channel="inputChannel" ]]><co id="resxml2-co" linkends="resxml2" /><![CDATA[
|
||||
output-channel="outputChannel" ]]><co id="resxml3-co" linkends="resxml3" /><![CDATA[
|
||||
discard-channel="discardChannel" ]]><co id="resxml4-co" linkends="resxml4" /><![CDATA[
|
||||
release-partial-sequences="true" ]]><co id="resxml5-co" linkends="resxml5" /><![CDATA[
|
||||
message-store="messageStore" ]]><co id="resxml6-co" linkends="resxml6" /><![CDATA[
|
||||
send-partial-result-on-expiry="true" ]]><co id="resxml7-co"
|
||||
linkends="resxml7" /><![CDATA[
|
||||
send-timeout="86420000" ]]><co id="resxml10-co" linkends="resxml10" /><![CDATA[ /> ]]></programlisting>
|
||||
|
||||
<para><calloutlist>
|
||||
<callout arearefs="resxml1-co" id="resxml1">
|
||||
<para>The id of the resequencer is
|
||||
<emphasis>optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="resxml2-co" id="resxml2">
|
||||
<para>The input channel of the resequencer.
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="resxml3-co" id="resxml3">
|
||||
<para>The channel to which the resequencer will send the reordered
|
||||
messages. <emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="resxml4-co" id="resxml4">
|
||||
<para>The channel to which the resequencer will send the messages that
|
||||
timed out (if <code>send-partial-result-on-timeout</code> is
|
||||
<emphasis>false)</emphasis>. <emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="resxml5-co" id="resxml5">
|
||||
|
||||
|
||||
<para>Whether to send out ordered sequences as soon as they are
|
||||
available, or only after the whole message group arrives.
|
||||
<emphasis>Optional (false by default)</emphasis>.</para>
|
||||
|
||||
If this flag is not specified (so a complete sequence is defined by the sequence headers) then it may make sense to provide a custom
|
||||
|
||||
<interfacename>Comparator</interfacename>
|
||||
|
||||
to be used to order the messages when sending (use the XML attribute
|
||||
|
||||
<literal>comparator</literal>
|
||||
|
||||
to point to a bean definition). If
|
||||
|
||||
<literal>release-partial-sequences</literal>
|
||||
|
||||
is true then there is no way with a custom comparator to define a partial sequence. To do that you would have to provide a
|
||||
|
||||
<literal>release-strategy</literal>
|
||||
|
||||
(also a reference to another bean definition, either a POJO or a
|
||||
|
||||
<interfacename>ReleaseStrategy</interfacename>
|
||||
|
||||
).
|
||||
</callout>
|
||||
|
||||
<callout arearefs="resxml6-co" id="resxml6">
|
||||
<para>A reference to a <code>MessageGroupStore</code> that can be
|
||||
used to store groups of messages under their correlation key until
|
||||
they are complete. <emphasis>Optional</emphasis> with default a
|
||||
volatile in-memory store.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="resxml7-co" id="resxml7">
|
||||
<para>Whether, upon the expiration of the group, the ordered group
|
||||
should be sent out (even if some of the messages are missing).
|
||||
<emphasis>Optional (false by default)</emphasis>. See <xref
|
||||
linkend="reaper" />.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="resxml10-co" id="resxml10">
|
||||
<para>The timeout for sending out messages.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
</calloutlist></para>
|
||||
|
||||
<note>
|
||||
Since there is no custom behavior to be implemented in Java classes for resequencers, there is no annotation support for it.
|
||||
</note>
|
||||
</section>
|
||||
</section>
|
||||
95
src/reference/docbook/resource.xml
Normal file
@@ -0,0 +1,95 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="resource"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Resource Support</title>
|
||||
|
||||
<section id="resource-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
The <emphasis>Resource Inbound Channel Adapter</emphasis> builds upon Spring's <classname>Resource</classname> abstraction to
|
||||
support greater flexibility across a variety of actual types of underlying resources, such as a file, a URL,
|
||||
or a class path resource. Therefore, it's similar to but more generic than the
|
||||
<emphasis>File Inbound Channel Adapter</emphasis>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="resource-inbound-channel-adapter">
|
||||
<title>Resource Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The <emphasis>Resource Inbound Channel Adapter</emphasis> is a polling adapter that creates a <classname>Message</classname>
|
||||
whose payload is a collection of <classname>Resource</classname> objects.
|
||||
</para>
|
||||
<para>
|
||||
<classname>Resource</classname> objects are resolved based on the pattern specified using the <code>pattern</code> attribute.
|
||||
The collection of resolved <classname>Resource</classname> objects is then sent as a payload within a
|
||||
<classname>Message</classname> to the adapter's channel. That is one major difference between <emphasis>Resource Inbound Channel Adapter</emphasis>
|
||||
and <emphasis>File Inbound Channel Adapter</emphasis>; the latter buffers File objects and sends a single <classname>File</classname> object per
|
||||
<classname>Message</classname>.
|
||||
</para>
|
||||
<para>
|
||||
Below is an example of a very simple configuration which will find all files ending with the 'properties'
|
||||
extension in the <code>foo.bar</code> package available on the classpath and will send them as
|
||||
the payload of a Message to the channel named '<code>resultChannel</code>':
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:resource-inbound-channel-adapter id="resourceAdapter"
|
||||
channel="resultChannel"
|
||||
pattern="classpath:foo/bar/*.properties">
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int:resource-inbound-channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The <emphasis>Resource Inbound Channel Adapter</emphasis> relies on the
|
||||
<classname>org.springframework.core.io.support.ResourcePatternResolver</classname> strategy interface to resolve the provided pattern.
|
||||
It defaults to an instance of the current <classname>ApplicationContext</classname>. However you may provide a reference to an instance
|
||||
of your own implementation of <classname>ResourcePatternResolver</classname> using the <code>pattern-resolver</code> attribute:
|
||||
<programlisting language="xml"><![CDATA[<int:resource-inbound-channel-adapter id="resourceAdapter"
|
||||
channel="resultChannel"
|
||||
pattern="classpath:foo/bar/*.properties"
|
||||
pattern-resolver="myPatternResolver">
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int:resource-inbound-channel-adapter>
|
||||
|
||||
<bean id="myPatternResolver" class="org.example.MyPatternResolver"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
You may have a use case where you need to further filter the collection of resources
|
||||
resolved by the <classname>ResourcePatternResolver</classname>. For example, you may want to prevent resources
|
||||
that were resolved already from appearing in a collection of resolved resources ever again. On the other hand
|
||||
your resources might be updated rather often and you <emphasis>do</emphasis> want them to be picked up again.
|
||||
In other words there is a valid use case for defining an additional filter as well as disabling filtering altogether.
|
||||
You can provide your own implementation of the <classname>org.springframework.integration.util.CollectionFilter</classname>
|
||||
strategy interface:
|
||||
<programlisting language="java"><![CDATA[public interface CollectionFilter<T> {
|
||||
|
||||
Collection<T> filter(Collection<T> unfilteredElements);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
As you can see the <classname>CollectionFilter</classname> receives a collection of un-filtered elements
|
||||
(which would be <classname>Resource</classname> objects in this case), and it returns a collection of
|
||||
filtered elements of that same type.
|
||||
|
||||
</para>
|
||||
<para>
|
||||
If you are defining the adapter via XML but you do not specify a filter reference, a default implementation of
|
||||
<classname>CollectionFilter</classname> will be used by the <emphasis>Resource Inbound Channel Adapter</emphasis>.
|
||||
The implementation class of that default filter is <classname>org.springframework.integration.util.AcceptOnceCollectionFilter</classname>.
|
||||
It remembers the elements passed in the previous invocation in order to avoid returning those elements more than once.
|
||||
</para>
|
||||
<para>
|
||||
To inject your own implementation of <classname>CollectionFilter</classname> instead, use the <code>filter</code> attribute.
|
||||
<programlisting language="xml"><![CDATA[<int:resource-inbound-channel-adapter id="resourceAdapter"
|
||||
channel="resultChannel"
|
||||
pattern="classpath:foo/bar/*.properties"
|
||||
filter="myFilter">
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int:resource-inbound-channel-adapter>
|
||||
|
||||
<bean id="myFilter" class="org.example.MyFilter"/>]]></programlisting>
|
||||
|
||||
If you don't need any filtering and want to disable even the default <classname>CollectionFilter</classname> strategy,
|
||||
simply provide an empty value for the filter attribute (e.g., <code>filter=""</code>)
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
17
src/reference/docbook/resources.xml
Normal file
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<appendix xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="resources"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Additional Resources</title>
|
||||
|
||||
<section id="resources-home">
|
||||
<title>Spring Integration Home</title>
|
||||
<para>
|
||||
The definitive source of information about Spring Integration is the
|
||||
<ulink url="http://www.springsource.org/spring-integration">Spring Integration Home</ulink> at
|
||||
<ulink url="http://www.springsource.org">http://www.springsource.org</ulink>. That site serves as a hub of
|
||||
information and is the best place to find up-to-date announcements about the project as well as links to
|
||||
articles, blogs, and new sample applications.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</appendix>
|
||||
66
src/reference/docbook/rmi.xml
Normal file
@@ -0,0 +1,66 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="rmi"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>RMI Support</title>
|
||||
|
||||
<section id="rmi-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
This Chapter explains how to use RMI specific channel adapters to distribute a system over multiple JVMs. The first section will deal with sending messages over RMI. The second section shows how to receive messages over RMI. The last section shows how to define rmi channel adapters through the namespace support.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="rmi-outbound">
|
||||
<title>Outbound RMI</title>
|
||||
<para>
|
||||
To send messages from a channel over RMI, simply define an <classname>RmiOutboundGateway</classname>. This gateway will use Spring's RmiProxyFactoryBean internally to create a proxy for a remote gateway. Note that to invoke a remote interface that doesn't use Spring Integration you should use a service activator in combination with Spring's RmiProxyFactoryBean.
|
||||
</para>
|
||||
<para>
|
||||
To configure the outbound gateway write a bean definition like this:
|
||||
<programlisting language="xml"><![CDATA[ <bean id="rmiOutGateway" class=org.spf.integration.rmi.RmiOutboundGateway>
|
||||
<constructor-arg value="rmi://host"/>
|
||||
<property name="replyChannel" value="replies"/>
|
||||
</bean>]]>
|
||||
</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="rmi-inbound">
|
||||
<title>Inbound RMI</title>
|
||||
<para>
|
||||
To receive messages over RMI you need to use a <classname>RmiInboundGateway</classname>. This gateway can be configured like this
|
||||
<programlisting language="xml"><![CDATA[ <bean id="rmiOutGateway" class=org.spf.integration.rmi.RmiInboundGateway>
|
||||
<property name="requestChannel" value="requests"/>
|
||||
</bean>]]>
|
||||
</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="rmi-namespace">
|
||||
<title>RMI namespace support</title>
|
||||
<para>
|
||||
To configure the inbound gateway you can choose to use the namespace support for it. The following code snippet shows the different configuration options that are supported.
|
||||
<programlisting language="xml"><![CDATA[ <int-rmi:inbound-gateway id="gatewayWithDefaults" request-channel="testChannel"/>
|
||||
|
||||
<int-rmi:inbound-gateway id="gatewayWithCustomProperties" request-channel="testChannel"
|
||||
expect-reply="false" request-timeout="123" reply-timeout="456"/>
|
||||
|
||||
<int-rmi:inbound-gateway id="gatewayWithHost" request-channel="testChannel"
|
||||
registry-host="localhost"/>
|
||||
|
||||
<int-rmi:inbound-gateway id="gatewayWithPort" request-channel="testChannel"
|
||||
registry-port="1234"/>
|
||||
|
||||
<int-rmi:inbound-gateway id="gatewayWithExecutorRef" request-channel="testChannel"
|
||||
remote-invocation-executor="invocationExecutor"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To configure the outbound gateway you can use the namespace support as well. The following code snippet shows the different configuration for an outbound rmi gateway.
|
||||
<programlisting language="xml"><![CDATA[ <int-rmi:outbound-gateway id="gateway"
|
||||
request-channel="localChannel"
|
||||
remote-channel="testChannel"
|
||||
host="localhost"/>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
953
src/reference/docbook/router.xml
Normal file
@@ -0,0 +1,953 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="router"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Routers</title>
|
||||
<section id="router-overview">
|
||||
<title>Overview</title>
|
||||
<para>
|
||||
Routers are a crucial element in many messaging architectures. They consume
|
||||
Messages from a Message Channel and forward each consumed message to one or
|
||||
more different Message Channel depending on a set of conditions.
|
||||
</para>
|
||||
<para>
|
||||
Spring Integration provides the following routers out-of-the-box:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='router-implementations-payloadtyperouter'>Payload Type Router</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='router-implementations-headervaluerouter'>Header Value Router</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='router-implementations-recipientlistrouter'>Recipient List Router</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='xml-xpath-routing'>XPath Router (Part of the XML Module)</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='router-implementations-exception-router'>Error Message Exception Type Router</link></emphasis></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis><link linkend='router-namespace'>(Generic) Router</link></emphasis></para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
Router implementations share many configuration parameters. Yet, certain differences
|
||||
exist between routers. Furthermore, the availability of configuration parameters
|
||||
depends on whether Routers are used inside or outside of a chain. In order to
|
||||
provide a quick overview, all available attributes are listed in the 2 tables
|
||||
below.
|
||||
</para>
|
||||
<table><title>Routers Outside of a Chain</title>
|
||||
<tgroup cols="7">
|
||||
<colspec colnum="1" colname="col01" colwidth="3*"/>
|
||||
<colspec colnum="2" colname="col02" colwidth="1*" align="center"/>
|
||||
<colspec colnum="3" colname="col03" colwidth="1*" align="center"/>
|
||||
<colspec colnum="4" colname="col04" colwidth="1*" align="center"/>
|
||||
<colspec colnum="5" colname="col05" colwidth="1*" align="center"/>
|
||||
<colspec colnum="6" colname="col06" colwidth="1*" align="center"/>
|
||||
<colspec colnum="7" colname="col07" colwidth="1*" align="center"/>
|
||||
<thead>
|
||||
<row>
|
||||
<entry>Attribute</entry>
|
||||
<entry>router</entry>
|
||||
<entry>header value router</entry>
|
||||
<entry>xpath router</entry>
|
||||
<entry>payload type router</entry>
|
||||
<entry>recipient list router</entry>
|
||||
<entry>exception type router</entry>
|
||||
</row>
|
||||
</thead>
|
||||
<tbody>
|
||||
<row>
|
||||
<entry>apply-sequence</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>x<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>default-output-channel</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>resolution-required</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>ignore-send-failures</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>timeout</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>id</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>auto-startup</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>input-channel</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>order</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>method</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>ref</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>expression</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>header-name</entry>
|
||||
<entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>evaluate-as-string</entry>
|
||||
<entry></entry><entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>xpath-expression-ref</entry>
|
||||
<entry></entry><entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>converter</entry>
|
||||
<entry></entry><entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
</tbody>
|
||||
</tgroup>
|
||||
</table>
|
||||
<table><title>Routers Inside of a Chain</title>
|
||||
<tgroup cols="7">
|
||||
<colspec colnum="1" colname="col01" colwidth="3*"/>
|
||||
<colspec colnum="2" colname="col02" colwidth="1*" align="center"/>
|
||||
<colspec colnum="3" colname="col03" colwidth="1*" align="center"/>
|
||||
<colspec colnum="4" colname="col04" colwidth="1*" align="center"/>
|
||||
<colspec colnum="5" colname="col05" colwidth="1*" align="center"/>
|
||||
<colspec colnum="6" colname="col06" colwidth="1*" align="center"/>
|
||||
<colspec colnum="7" colname="col07" colwidth="1*" align="center"/>
|
||||
<thead>
|
||||
<row>
|
||||
<entry>Attribute</entry>
|
||||
<entry>router</entry>
|
||||
<entry>header value router</entry>
|
||||
<entry>xpath router</entry>
|
||||
<entry>payload type router</entry>
|
||||
<entry>recipient list router</entry>
|
||||
<entry>exception type router</entry>
|
||||
</row>
|
||||
</thead>
|
||||
<tbody>
|
||||
<row>
|
||||
<entry>apply-sequence</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>x<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>default-output-channel</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>resolution-required</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>ignore-send-failures</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>timeout</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry><imagedata fileref="images/tickmark.png"/></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>id</entry>
|
||||
<entry></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>auto-startup</entry>
|
||||
<entry></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>input-channel</entry>
|
||||
<entry></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>order</entry>
|
||||
<entry></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>method</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>ref</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>expression</entry>
|
||||
<entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>header-name</entry>
|
||||
<entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>evaluate-as-string</entry>
|
||||
<entry></entry><entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>xpath-expression-ref</entry>
|
||||
<entry></entry><entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
<row>
|
||||
<entry>converter</entry>
|
||||
<entry></entry><entry></entry><entry><imagedata fileref="images/tickmark.png"/></entry><entry></entry><entry></entry><entry></entry>
|
||||
</row>
|
||||
</tbody>
|
||||
</tgroup>
|
||||
</table>
|
||||
<important>
|
||||
<para>
|
||||
Router parameters have been more standardized across all router implementations
|
||||
with Spring Integration 2.1. Consequently, there are a few minor changes that
|
||||
leave the possibility of breaking older Spring Integration based applications.
|
||||
</para>
|
||||
<para>
|
||||
Since Spring Integration 2.1 the <code>ignore-channel-name-resolution-failures</code>
|
||||
attribute is removed in favor of consolidating its behavior with the
|
||||
<code>resolution-required</code> attribute. Also, the <code>resolution-required</code> attribute
|
||||
now defaults to <code>true</code>.
|
||||
</para>
|
||||
<para>
|
||||
Prior to these changes, the <code>resolution-required</code> attribute defaulted
|
||||
to <code>false</code> causing messages to be silently dropped when no channel was
|
||||
resolved and no <code>default-output-channel</code> was set.
|
||||
|
||||
The new behavior will require at least one resolved channel and by default
|
||||
will throw an <code>MessageDeliveryException</code> if no channel was
|
||||
determined (or an attempt to send was not successful).
|
||||
</para>
|
||||
<para>
|
||||
If you do desire to drop messages silently simply set <code>default-output-channel="nullChannel"</code>.
|
||||
</para>
|
||||
</important>
|
||||
</section>
|
||||
<section id="router-common-parameters">
|
||||
<title id="router-common-parameters.title">Common Router Parameters</title>
|
||||
<section id="router-common-parameters-all">
|
||||
<title>Inside and Outside of a Chain</title>
|
||||
<para>The following parameters are valid for all routers inside and outside of
|
||||
chains.
|
||||
</para>
|
||||
<variablelist>
|
||||
<varlistentry><term><emphasis role="bold">apply-sequence</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
This attribute specifies whether sequence number and
|
||||
size headers should be added to each Message. This
|
||||
<emphasis>optional</emphasis> attribute defaults
|
||||
to <emphasis>false</emphasis>.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
<varlistentry><term><emphasis role="bold">default-output-channel</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
If set, this attribute provides a reference to the
|
||||
channel, where Messages should be sent, if channel
|
||||
resolution fails to return any channels. If no default
|
||||
output channel is provided, the router will throw an Exception.
|
||||
If you would like to silently drop those messages instead,
|
||||
add the <code>nullChannel</code> as the default output
|
||||
channel attribute value.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
<varlistentry><term><emphasis role="bold">resolution-required</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
If <emphasis>true</emphasis> this attribute specifies
|
||||
that channel names must always be successfully resolved
|
||||
to channel instances that exist. If set to
|
||||
<emphasis>true</emphasis>, a <code>MessagingException</code>
|
||||
will be raised, in case the channel cannot be resolved.
|
||||
Setting this attribute to <emphasis>false</emphasis>,
|
||||
will cause any unresovable channels to be ignored. This
|
||||
<emphasis>optional</emphasis> attribute will, if not
|
||||
explicitly set, default to <emphasis>true</emphasis>.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
<varlistentry><term><emphasis role="bold">ignore-send-failures</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
If set to <emphasis>true</emphasis>, failures to send to a
|
||||
message channel will be ignored. If set to <emphasis>false</emphasis>,
|
||||
a <classname>MessageDeliveryException</classname> will
|
||||
be thrown instead, and if the router resolves more than
|
||||
one channel, any subsequent channels will not receive
|
||||
the message.
|
||||
</para>
|
||||
<para>
|
||||
The exact behavior of this attribute depends on the type
|
||||
of the <code>Channel</code> messages are sent to. For
|
||||
example, when using direct channels (single threaded),
|
||||
send-failures can be caused by exceptions thrown by components
|
||||
much further down-stream. However, when sending
|
||||
messages to a simple queue channel (asynchronous) the
|
||||
likelihood of an exception to be thrown is rather remote.
|
||||
</para>
|
||||
<note>
|
||||
While most routers will route to a single channel, they
|
||||
are allowed to return more than one channel name. The
|
||||
<code>recipient-list-router</code>, for instance, does
|
||||
exactly that.
|
||||
|
||||
If you set this attribute to <emphasis>true</emphasis>
|
||||
on a router that only routes to a single channel, any
|
||||
caused exception is simply swallowed, which usually makes
|
||||
little sense to do. In that case it would be better to
|
||||
catch the exception in an error flow at the flow entry
|
||||
point.
|
||||
|
||||
Therefore, setting the <code>ignore-send-failures</code>
|
||||
attribute to <emphasis>true</emphasis> usually makes
|
||||
more sense when the router implementation returns more
|
||||
than one channel name, because the other channel(s)
|
||||
following the one that fails would still receive the Message.
|
||||
</note>
|
||||
<para>
|
||||
This attribute defaults to <emphasis>false</emphasis>.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
<varlistentry><term><emphasis role="bold">timeout</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
The <code>timeout</code> attribute specifies the maximum
|
||||
amount of time in milliseconds to wait, when
|
||||
sending Messages to the target Message Channels. By default
|
||||
the send operation will block indefinitely.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
</variablelist>
|
||||
</section>
|
||||
<section id="router-common-parameters-top">
|
||||
<title>Top-Level (Outside of a Chain)</title>
|
||||
<para>
|
||||
The following parameters are valid only across all top-level routers that are
|
||||
ourside of chains.
|
||||
</para>
|
||||
|
||||
<variablelist>
|
||||
<varlistentry><term><emphasis role="bold">id</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
Identifies the underlying Spring bean definition which
|
||||
in case of Routers is an instance of EventDrivenConsumer or
|
||||
PollingConsumer depending on whether the Router's
|
||||
<emphasis>input-channel</emphasis> is a
|
||||
<emphasis>SubscribableChannel</emphasis> or
|
||||
<emphasis>PollableChannel</emphasis>, respectively.
|
||||
This is an <emphasis>optional</emphasis> attribute.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
<varlistentry><term><emphasis role="bold">auto-startup</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
This <code>Lifecycle</code> attribute signaled if this
|
||||
component should be started during startup of the Application
|
||||
Context. This <emphasis>optional</emphasis>
|
||||
attribute defaults to <emphasis>true</emphasis>.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
<varlistentry><term><emphasis role="bold">input-channel</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
The receiving Message channel of this endpoint.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
<varlistentry><term><emphasis role="bold">order</emphasis></term>
|
||||
<listitem>
|
||||
<para>
|
||||
This attribute defines the order for invocation when
|
||||
this endpoint is connected as a subscriber to a channel.
|
||||
This is particularly relevant when that channel is using a
|
||||
<emphasis>failover</emphasis> dispatching strategy. It
|
||||
has no effect when this endpoint itself is a Polling
|
||||
Consumer for a channel with a queue.
|
||||
</para>
|
||||
</listitem>
|
||||
</varlistentry>
|
||||
</variablelist>
|
||||
|
||||
</section>
|
||||
</section>
|
||||
<section id="router-implementations">
|
||||
<title>Router Implementations</title>
|
||||
<para>
|
||||
Since content-based routing often requires some domain-specific logic, most use-cases will require
|
||||
Spring Integration's options for delegating to POJOs using the XML namespace support and/or Annotations.
|
||||
Both of these are discussed below, but first we present a couple implementations that are available
|
||||
out-of-the-box since they fulfill common requirements.
|
||||
</para>
|
||||
<section id="router-implementations-payloadtyperouter">
|
||||
<title>PayloadTypeRouter</title>
|
||||
<para>
|
||||
A <classname>PayloadTypeRouter</classname> will send Messages to the channel as defined by payload-type
|
||||
mappings.
|
||||
<programlisting language="xml"><![CDATA[<bean id="payloadTypeRouter"
|
||||
class="org.springframework.integration.router.PayloadTypeRouter">
|
||||
<property name="channelIdentifierMap">
|
||||
<map>
|
||||
<entry key="java.lang.String" value-ref="stringChannel"/>
|
||||
<entry key="java.lang.Integer" value-ref="integerChannel"/>
|
||||
</map>
|
||||
</property>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Configuration of the <classname>PayloadTypeRouter</classname> is also supported via the namespace provided by Spring Integration (see <xref linkend="configuration-namespace"/>),
|
||||
which essentially simplifies configuration by combining the <code><router/></code> configuration and its corresponding implementation
|
||||
defined using a <code><bean/></code> element
|
||||
into a single and more concise configuration element.
|
||||
The example below demonstrates a <classname>PayloadTypeRouter</classname> configuration which is equivalent to the one above using the namespace support:
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:payload-type-router input-channel="routingChannel">
|
||||
<int:mapping type="java.lang.String" channel="stringChannel" />
|
||||
<int:mapping type="java.lang.Integer" channel="integerChannel" />
|
||||
</int:payload-type-router>]]></programlisting>
|
||||
</section>
|
||||
<section id="router-implementations-headervaluerouter">
|
||||
<title>HeaderValueRouter</title>
|
||||
<para>
|
||||
A <classname>HeaderValueRouter</classname> will send Messages to the channel based on the individual header value mappings.
|
||||
When a <code>HeaderValueRouter</code> is created it is initialized with the <emphasis>name</emphasis> of the header to be evaluated.
|
||||
The <emphasis>value</emphasis> of the header could be one of two things:</para>
|
||||
<para>
|
||||
1. Arbitrary value
|
||||
</para>
|
||||
<para>
|
||||
2. Channel name
|
||||
</para>
|
||||
<para>
|
||||
If arbitrary then additional mappings for these header values to channel names is required, otherwise no additional configuration is needed.
|
||||
</para>
|
||||
<para>
|
||||
Spring Integration provides a simple namespace-based XML configuration to configure a <classname>HeaderValueRouter</classname>.
|
||||
The example below demonstrates two types of namespace-based configuration for the <classname>HeaderValueRouter</classname>.
|
||||
</para>
|
||||
<para><emphasis>1. Configuration where mapping of header values to channels is required</emphasis></para>
|
||||
<programlisting language="xml"><![CDATA[<int:header-value-router input-channel="routingChannel" header-name="testHeader">
|
||||
<int:mapping value="someHeaderValue" channel="channelA" />
|
||||
<int:mapping value="someOtherHeaderValue" channel="channelB" />
|
||||
</int:header-value-router>]]></programlisting>
|
||||
<para>
|
||||
During the resolution process this router may encounter channel
|
||||
resolution failures, causing an exception. If you want to suppress
|
||||
such exceptions and send unresolved messages to the default output
|
||||
channel (identified with the <code>default-output-channel</code>
|
||||
attribute) set <code>resolution-required</code> to <code>false</code>.
|
||||
</para>
|
||||
<para>
|
||||
Normally, messages for which the header value is not explicitly
|
||||
mapped to a channel will be sent to the <code>default-output-channel</code>.
|
||||
However, in cases where the header value is mapped to a channel
|
||||
name but the channel cannot be resolved, setting the <code>resolution-required</code>
|
||||
attribute to <code>false</code> will result in routing such messages
|
||||
to the <code>default-output-channel</code>.
|
||||
</para>
|
||||
|
||||
<important>
|
||||
With Spring Integration 2.1 the attribute was changed from
|
||||
<code>ignore-channel-name-resolution-failures</code> to
|
||||
<code>resolution-required</code>. Attribute <code>resolution-required</code>
|
||||
will default to <code>true</code>.
|
||||
</important>
|
||||
|
||||
<para><emphasis>2. Configuration where mapping of header values to channel names
|
||||
is not required since header values themselves represent channel names</emphasis>
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:header-value-router input-channel="routingChannel" header-name="testHeader"/>]]></programlisting>
|
||||
<note>
|
||||
<para>
|
||||
Since Spring Integration 2.1 the behavior of resolving channels is
|
||||
more explicit. For example, if you ommit the <code>default-output-channel</code> attribute
|
||||
and the Router was unable to resolve at least one valid channel, and any channel name resolution
|
||||
failures were ignored by setting <code>resolution-required</code> to <code>false</code>, then a
|
||||
<code>MessageDeliveryException</code> is thrown.
|
||||
</para>
|
||||
<para>
|
||||
Basically, by default the Router must be able to route messages
|
||||
successfully to at least one channel. If you really want to
|
||||
drop messages, you must also have <code>default-output-channel</code>
|
||||
set to <code>nullChannel</code>.
|
||||
</para>
|
||||
</note>
|
||||
</section>
|
||||
<section id="router-implementations-recipientlistrouter">
|
||||
<title>RecipientListRouter</title>
|
||||
<para>
|
||||
A <classname>RecipientListRouter</classname> will send each received Message to a statically defined
|
||||
list of Message Channels:
|
||||
<programlisting language="xml"><![CDATA[<bean id="recipientListRouter"
|
||||
class="org.springframework.integration.router.RecipientListRouter">
|
||||
<property name="channels">
|
||||
<list>
|
||||
<ref bean="channel1"/>
|
||||
<ref bean="channel2"/>
|
||||
<ref bean="channel3"/>
|
||||
</list>
|
||||
</property>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration also provides namespace support for the <classname>RecipientListRouter</classname> configuration (see <xref linkend="configuration-namespace"/>)
|
||||
as the example below demonstrates.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:recipient-list-router id="customRouter" input-channel="routingChannel"
|
||||
timeout="1234"
|
||||
ignore-send-failures="true"
|
||||
apply-sequence="true">
|
||||
<int:recipient channel="channel1"/>
|
||||
<int:recipient channel="channel2"/>
|
||||
</int:recipient-list-router>]]></programlisting>
|
||||
|
||||
<note>
|
||||
The 'apply-sequence' flag here has the same effect as it does for a publish-subscribe-channel,
|
||||
and like a publish-subscribe-channel, it is disabled by default on the recipient-list-router. Refer to
|
||||
<xref linkend="channel-configuration-pubsubchannel"/> for more information.
|
||||
</note>
|
||||
<para>
|
||||
Another convenient option when configuring a <classname>RecipientListRouter</classname> is to use Spring Expression Language (SpEL) support
|
||||
as selectors for individual recipient channels. This is similar to using a Filter at the beginning of 'chain' to act as a "Selective Consumer".
|
||||
However, in this case, it's all combined rather concisely into the router's configuration.
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:recipient-list-router id="customRouter" input-channel="routingChannel">
|
||||
<int:recipient channel="channel1" selector-expression="payload.equals('foo')"/>
|
||||
<int:recipient channel="channel2" selector-expression="headers.containsKey('bar')"/>
|
||||
</int:recipient-list-router>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the above configuration a SpEL expression identified by the <code>selector-expression</code> attribute will be evaluated to determine if this recipient
|
||||
should be included in the recipient list for a given input Message. The evaluation result of the expression must be a boolean. If this
|
||||
attribute is not defined, the channel will always be among the list of recipients.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="router-implementations-xpath-router">
|
||||
<title>XPath Router</title>
|
||||
<para>The XPath Router is part of the XML Module. As such, please read chapter
|
||||
<emphasis><xref linkend='xml-xpath-routing' endterm="xml-xpath-routing.title"/></emphasis>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="router-implementations-exception-router">
|
||||
<title>Routing and Error handling</title>
|
||||
|
||||
<para>
|
||||
Spring Integration also provides a special type-based router called <classname>ErrorMessageExceptionTypeRouter</classname> for routing
|
||||
Error Messages (Messages whose <code>payload</code> is a <classname>Throwable</classname> instance).
|
||||
<classname>ErrorMessageExceptionTypeRouter</classname> is very similar to the <classname>PayloadTypeRouter</classname>.
|
||||
In fact they are almost identical. The only difference is that while <classname>PayloadTypeRouter</classname> navigates
|
||||
the instance hierarchy of a payload instance (e.g., <code>payload.getClass().getSuperclass()</code>) to find the most
|
||||
specific type/channel mappings, the <classname>ErrorMessageExceptionTypeRouter</classname> navigates the hierarchy of
|
||||
'exception causes' (e.g., <code>payload.getCause()</code>) to find the most specific <classname>Throwable</classname> type/channel mappings.
|
||||
</para>
|
||||
<para>
|
||||
Below is a sample configuration for <classname>ErrorMessageExceptionTypeRouter</classname>.
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:exception-type-router input-channel="inputChannel"
|
||||
default-output-channel="defaultChannel">
|
||||
<int:mapping exception-type="java.lang.IllegalArgumentException"
|
||||
channel="illegalChannel"/>
|
||||
<int:mapping exception-type="java.lang.NullPointerException"
|
||||
channel="npeChannel"/>
|
||||
</int:exception-type-router>
|
||||
|
||||
<int:channel id="illegalChannel" />
|
||||
<int:channel id="npeChannel" />]]></programlisting>
|
||||
</section>
|
||||
</section>
|
||||
<section id="router-namespace">
|
||||
<title>Configuring (Generic) Router</title>
|
||||
<section>
|
||||
<title>Configuring a Content Based Router with XML</title>
|
||||
<para>
|
||||
The "router" element provides a simple way to connect a router to an input channel and also accepts the
|
||||
optional <code>default-output-channel</code> attribute. The <code>ref</code> attribute references the bean name of a custom Router implementation
|
||||
(extending <classname>AbstractMessageRouter</classname>):
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:router ref="payloadTypeRouter" input-channel="input1"
|
||||
default-output-channel="defaultOutput1"/>
|
||||
|
||||
<int:router ref="recipientListRouter" input-channel="input2"
|
||||
default-output-channel="defaultOutput2"/>
|
||||
|
||||
<int:router ref="customRouter" input-channel="input3"
|
||||
default-output-channel="defaultOutput3"/>
|
||||
|
||||
<beans:bean id="customRouterBean class="org.foo.MyCustomRouter"/>]]></programlisting>
|
||||
|
||||
<para>
|
||||
Alternatively, <code>ref</code> may point to a simple POJO that contains the @Router annotation (see below), or the
|
||||
<code>ref</code> may be combined with an explicit <code>method</code> name. Specifying a <code>method</code> applies the same behavior
|
||||
described in the @Router annotation section below.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:router input-channel="input" ref="somePojo" method="someMethod"/>]]></programlisting>
|
||||
|
||||
<para>
|
||||
Using a <code>ref</code> attribute is generally recommended if the custom router implementation is referenced in other
|
||||
<code><router></code> definitions. However if the custom router implementation should be scoped to a
|
||||
single definition of the <code><router></code>, you may provide an inner bean definition:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:router method="someMethod" input-channel="input3"
|
||||
default-output-channel="defaultOutput3">
|
||||
<beans:bean class="org.foo.MyCustomRouter"/>
|
||||
</int:router>]]></programlisting>
|
||||
|
||||
<note>
|
||||
<para>
|
||||
Using both the <code>ref</code> attribute and an inner handler definition in the same <code><router></code> configuration
|
||||
is not allowed, as it creates an ambiguous condition, and an Exception will be thrown.
|
||||
</para>
|
||||
</note>
|
||||
<para>
|
||||
<emphasis>Routers and the Spring Expression Language (SpEL)</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
Sometimes the routing logic may be simple and writing a separate class for
|
||||
it and configuring it as a bean may seem like overkill. As of Spring Integration 2.0
|
||||
we offer an alternative where you can now use SpEL to implement simple
|
||||
computations that previously required a custom POJO router.
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
For more information about the Spring Expression Language, please
|
||||
refer to the respective chapter in the Spring Framework Reference
|
||||
Documentation at:
|
||||
</para>
|
||||
<para>
|
||||
<ulink url="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/expressions.html"/>
|
||||
</para>
|
||||
</note>
|
||||
<para>
|
||||
Generally a SpEL expression is evaluated and the result is mapped to
|
||||
a channel:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:router input-channel="inChannel" expression="payload.paymentType">
|
||||
<int:mapping value="CASH" channel="cashPaymentChannel"/>
|
||||
<int:mapping value="CREDIT" channel="authorizePaymentChannel"/>
|
||||
<int:mapping value="DEBIT" channel="authorizePaymentChannel"/>
|
||||
</int:router>]]></programlisting>
|
||||
|
||||
<para>
|
||||
To simplify things even more, the SpEL expression may evaluate to a channel name:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:router input-channel="inChannel" expression="payload + 'Channel'"/>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the above configuration the result channel will be computed by the SpEL
|
||||
expression which simply concatenates the value of the <code>payload</code>
|
||||
with the literal String 'Channel'.
|
||||
</para>
|
||||
<para>
|
||||
Another value of SpEL for configuring routers is that an expression can actually return a <classname>Collection</classname>,
|
||||
effectively making every <code><router></code> a <emphasis>Recipient List Router</emphasis>. Whenever the expression returns
|
||||
multiple channel values the Message will be forwarded to each channel.
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:router input-channel="inChannel" expression="headers.channels"/>]]></programlisting>
|
||||
|
||||
<para>
|
||||
In the above configuration, if the Message includes a header with the name 'channels' the value of which is a
|
||||
<classname>List</classname> of channel names then the Message will be sent to each channel in the list.
|
||||
|
||||
You may also find <emphasis>Collection Projection</emphasis> and <emphasis>Collection Selection</emphasis>
|
||||
expressions useful to select multiple channels. For further information,
|
||||
please see:
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<ulink url="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/expressions.html#d0e12084"/>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="router-annotation">
|
||||
<title>Configuring a Router with Annotations</title>
|
||||
<para>
|
||||
When using <interfacename>@Router</interfacename> to annotate a method, the method may return either a
|
||||
<interfacename>MessageChannel</interfacename> or <classname>String</classname> type. In the latter case,
|
||||
the endpoint will resolve the channel name as it does for the default output channel. Additionally, the method may return
|
||||
either a single value or a collection. If a collection is returned, the reply message will be sent to multiple
|
||||
channels. To summarize, the following method signatures are all valid.
|
||||
</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[@Router
|
||||
public MessageChannel route(Message message) {...}
|
||||
|
||||
@Router
|
||||
public List<MessageChannel> route(Message message) {...}
|
||||
|
||||
@Router
|
||||
public String route(Foo payload) {...}
|
||||
|
||||
@Router
|
||||
public List<String> route(Foo payload) {...}]]></programlisting>
|
||||
|
||||
<para>
|
||||
In addition to payload-based routing, a Message may be routed based on metadata available within the
|
||||
message header as either a property or attribute. In this case, a method annotated with <interfacename>@Router</interfacename>
|
||||
may include a parameter annotated with <interfacename>@Header</interfacename> which is mapped to a header value as illustrated
|
||||
below and documented in <xref linkend="annotations"/>.
|
||||
</para>
|
||||
|
||||
<programlisting language="java"><![CDATA[@Router
|
||||
public List<String> route(@Header("orderStatus") OrderStatus status)]]></programlisting>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<note>
|
||||
For routing of XML-based Messages, including XPath support, see <xref linkend="xml"/>.
|
||||
</note>
|
||||
|
||||
<section id="dynamic-routers">
|
||||
<title>Dynamic Routers</title>
|
||||
<para>
|
||||
So as you can see, Spring Integration provides quite a few different router configurations for common
|
||||
<emphasis>content-based routing</emphasis> use cases as well as the option of implementing custom routers as POJOs.
|
||||
For example <classname>PayloadTypeRouter</classname> provides a simple way to configure a router which computes <code>channels</code>
|
||||
based on the <code>payload type</code> of the incoming Message while <classname>HeaderValueRouter</classname> provides the
|
||||
same convenience in configuring a router which computes <code>channels</code> by evaluating the value
|
||||
of a particular Message Header. There are also <emphasis>expression-based</emphasis> (SpEL) routers where the <code>channel</code>
|
||||
is determined based on evaluating an expression. Thus, these type of routers exhibit some dynamic characteristics.
|
||||
</para>
|
||||
<para>
|
||||
However these routers all require <emphasis>static configuration</emphasis>. Even in the case of
|
||||
expression-based routers, the expression itself is defined as part of the router configuration which means that
|
||||
<emphasis>the same expression operating on the same value will always result in the computation of the same channel</emphasis>.
|
||||
This is acceptable in most cases since such routes are well defined and therefore predictable. But there are times when we
|
||||
need to change router configurations dynamically so message flows may be routed to a different channel.
|
||||
</para>
|
||||
<para><emphasis>Example:</emphasis></para>
|
||||
<para>
|
||||
You might want to bring down some part of your system for maintenance and temporarily re-reroute
|
||||
messages to a different message flow. Or you may want to introduce more granularity to your message flow by adding another
|
||||
route to handle a more concrete type of <classname>java.lang.Number</classname> (in the case of <classname>PayloadTypeRouter</classname>).
|
||||
</para>
|
||||
<para>
|
||||
Unfortunately with static router configuration to accomplish this, you would have to bring down your entire application,
|
||||
change the configuration of the router (change routes) and bring it back up. This is obviously not the solution.
|
||||
</para>
|
||||
<para>
|
||||
The <ulink url="http://www.eaipatterns.com/DynamicRouter.html">Dynamic Router</ulink>
|
||||
pattern describes the mechanisms by which one can change/configure routers dynamically without
|
||||
bringing down the system or individual routers.
|
||||
</para>
|
||||
<para>
|
||||
Before we get into the specifics of how this is accomplished in Spring Integration, let's quickly summarize the
|
||||
typical flow of the router, which consists of 3 simple steps:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>Step 1</emphasis> - Compute <code>channel identifier</code> which is a value calculated by the
|
||||
router once it receives the Message. Typically it is a <classname>String</classname> or and instance of the actual
|
||||
<classname>MessageChannel</classname>.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Step 2</emphasis> - Resolve <code>channel identifier</code> to <code>channel name</code>. We'll describe
|
||||
specifics of this process in a moment.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Step 3</emphasis> - Resolve <code>channel name</code> to the actual <classname>MessageChannel</classname> </para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<para>
|
||||
There is not much that can be done with regard to dynamic routing if Step 1 results in the actual instance of the
|
||||
<classname>MessageChannel</classname>, simply because the <classname>MessageChannel</classname> is the <emphasis>final product</emphasis> of any
|
||||
router's job. However, if Step 1 results in a <code>channel identifier</code> that is not an instance of <classname>MessageChannel</classname>,
|
||||
then there are quite a few possibilities to influence the process of deriving the <classname>Message Channel</classname>.
|
||||
Lets look at couple of the examples in the context of the 3 steps mentioned above:
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Payload Type Router</emphasis>
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:payload-type-router input-channel="routingChannel">
|
||||
<int:mapping type="java.lang.String" channel="channel1" />
|
||||
<int:mapping type="java.lang.Integer" channel="channel2" />
|
||||
</int:payload-type-router>]]></programlisting>
|
||||
|
||||
<para>
|
||||
Within the context of the Payload Type Router the 3 steps mentioned above would be realized as:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>Step 1</emphasis> - Compute <code>channel identifier</code> which is the fully qualified name of the payload type
|
||||
(e.g., java.lang.String).</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Step 2</emphasis> - Resolve <code>channel identifier</code> to <code>channel name</code> where
|
||||
the result of the previous step is used to select the appropriate value from the <emphasis>payload type mapping</emphasis>
|
||||
defined via <code>mapping</code> element.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Step 3</emphasis> - Resolve <code>channel name</code> to the actual instance of the
|
||||
<classname>MessageChannel</classname> as a reference to a bean within the Application Context
|
||||
(which is hopefully a <classname>MessageChannel</classname>) identified by the result of the
|
||||
previous step.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
In other words, each step feeds the next step until the process completes.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Header Value Router</emphasis>
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-value-router input-channel="inputChannel" header-name="testHeader">
|
||||
<int:mapping value="foo" channel="fooChannel" />
|
||||
<int:mapping value="bar" channel="barChannel" />
|
||||
</int:header-value-router>]]></programlisting>
|
||||
|
||||
<para>
|
||||
Similar to the PayloadTypeRouter:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>Step 1</emphasis> - Compute <code>channel identifier</code> which is the value of the header identified by the
|
||||
<code>header-name</code> attribute.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Step 2</emphasis> - Resolve <code>channel identifier</code> to <code>channel name</code> where
|
||||
the result of the previous step is used to select the appropriate value from the <emphasis>general mapping</emphasis>
|
||||
defined via <code>mapping</code> element.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Step 3</emphasis> - Resolve <code>channel name</code> to the actual instance of the
|
||||
<classname>MessageChannel</classname> as a reference to a bean within the Application Context
|
||||
(which is hopefully a <classname>MessageChannel</classname>) identified by the result of the
|
||||
previous step.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<para>
|
||||
The above two configurations of two different router types look almost identical.
|
||||
However if we look at the alternate configuration of the <classname>HeaderValueRouter</classname> we clearly see that
|
||||
there is no <code>mapping</code> sub element:
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<int:header-value-router input-channel="inputChannel" header-name="testHeader">]]></programlisting>
|
||||
<para>
|
||||
But the configuration is still perfectly valid. So the natural question is what about the mapping in the Step 2?
|
||||
</para>
|
||||
<para>
|
||||
What this means is that Step 2 is now an optional step. If <code>mapping</code> is not defined then the <code>channel identifier</code>
|
||||
value computed in Step 1 will automatically be treated as the <code>channel name</code>, which will now be resolved to the
|
||||
actual <classname>MessageChannel</classname> as in Step 3. What it also means is that Step 2 is one of the key steps to
|
||||
provide dynamic characteristics to the routers, since it introduces a process which
|
||||
<emphasis>allows you to change the way 'channel identifier' resolves to 'channel name'</emphasis>,
|
||||
thus influencing the process of determining the final instance of the <classname>MessageChannel</classname> from the initial
|
||||
<code>channel identifier</code>.
|
||||
</para>
|
||||
<para><emphasis>For Example:</emphasis> </para>
|
||||
<para>
|
||||
In the above configuration let's assume that the <code>testHeader</code> value is 'kermit' which is now a <code>channel identifier</code>
|
||||
(Step 1). Since there is no mapping in this router, resolving this <code>channel identifier</code> to a <code>channel name</code>
|
||||
(Step 2) is impossible and this <code>channel identifier</code> is now treated as <code>channel name</code>. However what if
|
||||
there was a mapping but for a different value? The end result would still be the same and that is:
|
||||
<emphasis>if a new value cannot be determined through the process of resolving the 'channel identifier' to a 'channel name',
|
||||
such 'channel identifier' becomes 'channel name'.</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
So all that is left is for Step 3 to resolve the <code>channel name</code> ('kermit') to an actual instance of the
|
||||
<classname>MessageChannel</classname> identified by this name. That basically involves a bean lookup
|
||||
for the name provided. So now all messages which contain the header/value pair as <code>testHeader=kermit</code>
|
||||
are going to be routed to a <classname>MessageChannel</classname> whose bean name (id) is 'kermit'.
|
||||
</para>
|
||||
<para>
|
||||
But what if you want to route these messages to the 'simpson' channel? Obviously changing a static configuration will work,
|
||||
but will also require bringing your system down. However if you had access to the <code>channel identifier</code> map, then you
|
||||
could just introduce a new mapping where the header/value pair is now <code>kermit=simpson</code>, thus allowing Step 2 to treat
|
||||
'kermit' as a <code>channel identifier</code> while resolving it to 'simpson' as the <code>channel name</code> .
|
||||
</para>
|
||||
<para>
|
||||
The same obviously applies for <classname>PayloadTypeRouter</classname>, where you can now remap or remove a particular <emphasis>payload type
|
||||
mapping</emphasis>. In fact, it applies to every other router, including <emphasis>expression-based</emphasis> routers, since their computed values
|
||||
will now have a chance to go through Step 2 to be additionally resolved to the actual <code>channel name</code>.
|
||||
</para>
|
||||
<para>
|
||||
In Spring Integration 2.0 the router hierarchy underwent significant refactoring, so that now any router that is a subclass of the
|
||||
<classname>AbstractMessageRouter</classname> (which includes all framework defined routers) is a Dynamic Router simply because the
|
||||
<code>channelIdentiferMap</code> is defined at the <classname>AbstractMessageRouter</classname> level. That map's setter method is
|
||||
exposed as a public method along with 'setChannelMapping' and 'removeChannelMapping' methods. These allow you to change/add/remove
|
||||
router mappings at runtime as long as you have a reference to the router itself. It also means that you could expose these same
|
||||
configuration options via JMX (see <xref linkend="jmx"/>) or the Spring Integration ControlBus (see <xref linkend="control-bus"/>) functionality.
|
||||
</para>
|
||||
|
||||
<section id="dynamic-routers-control-bus">
|
||||
<title>Manage Router Mappings using the Control Bus</title>
|
||||
<para>
|
||||
One way to manage the router mappings is through the <ulink url="http://www.eaipatterns.com/ControlBus.html">Control Bus</ulink>
|
||||
pattern which exposes a Control Channel where you can send
|
||||
control messages to manage and monitor Spring Integration components, including routers.
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
For more information about the Control Bus, please see chapter <emphasis><xref linkend="control-bus"/></emphasis>.
|
||||
</para>
|
||||
</note>
|
||||
<para>
|
||||
Typically you would send a control message asking to invoke a
|
||||
particular operation on a particular managed component (e.g. router). The two managed operations (methods) that are
|
||||
specific to changing the router resolution process are:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><code>public void setChannelMapping(String channelIdentifier, String channelName)</code> -
|
||||
will allow you to add a new or modify an existing mapping between <code>channel identifier</code> and <code>channel name</code></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><code>public void removeChannelMapping(String channelIdentifier)</code> -
|
||||
will allow you to remove a particular channel mapping, thus disconnecting the relationship between
|
||||
<code>channel identifier</code> and <code>channel name</code> </para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</section>
|
||||
<section id="dynamic-routers-jmx">
|
||||
<title>Manage Router Mappings using JMX</title>
|
||||
<para>
|
||||
You can also expose a router instance with Spring's JMX support, and then use your favorite JMX client (e.g., JConsole) to
|
||||
manage those operations (methods) for changing the router's configuration.
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
For more information about Spring Integration's JMX suppor, please see chapter <emphasis><xref linkend="jmx" endterm="jmx.title"/></emphasis>.
|
||||
</para>
|
||||
</note>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
714
src/reference/docbook/samples.xml
Normal file
@@ -0,0 +1,714 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<appendix xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="samples"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Spring Integration Samples</title>
|
||||
|
||||
<section id="samples-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
As of Spring Integration 2.0, the <emphasis>samples</emphasis> are no longer included with the
|
||||
Spring Integration distribution. Instead we have switched to a much simpler collaborative model that should promote
|
||||
better community participation and, ideally, more contributions. Samples now have a dedicated Git repository and a
|
||||
dedicated JIRA Issue Tracking system. Sample development will also have its own lifecycle which is not dependent on the
|
||||
lifecycle of the framework releases, although the repository will still be tagged with each major release for compatibility
|
||||
reasons.
|
||||
</para>
|
||||
<para>
|
||||
The great benefit to the community is that we can now add more samples and make them available to you right away
|
||||
without waiting for the next release. Having its own JIRA that is not tied to the the actual
|
||||
framework is also a great benefit. You now have a dedicated place to suggest samples as well as report issues with existing
|
||||
samples. Or, <emphasis> you may want to submit a sample to us</emphasis> as an attachment through the JIRA or, better, through
|
||||
the collaborative model that Git promotes. If we believe your sample adds value, we
|
||||
would be more then glad to add it to the 'samples' repository, properly crediting you as the author.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="samples-get">
|
||||
<title>Where to get Samples</title>
|
||||
<para>
|
||||
The Spring Integration Samples project is hosted on <ulink url="https://github.com/SpringSource/spring-integration-samples/">GitHub</ulink>.
|
||||
You can find the repository at:
|
||||
</para>
|
||||
<para>
|
||||
<ulink url="https://github.com/SpringSource/spring-integration-samples">https://github.com/SpringSource/spring-integration-samples</ulink>
|
||||
</para>
|
||||
<para>
|
||||
In order to check out or <emphasis>clone</emphasis> (Git parlance) the samples,
|
||||
please make sure you have a Git client installed on your system.
|
||||
There are several GUI-based products available for many platforms, e.g.
|
||||
<ulink url="http://eclipse.org/egit/">EGit</ulink> for the Eclipse IDE.
|
||||
A simple Google search will help you find them. Of course you can also just
|
||||
use the command line interface for <link linkend="http://git-scm.com/">Git</link>.
|
||||
</para>
|
||||
<note>
|
||||
If you need more information on how to install and/or use Git, please visit:
|
||||
<ulink url="http://git-scm.com/">http://git-scm.com/</ulink>.
|
||||
</note>
|
||||
<para>
|
||||
In order to checkout (clone in Git terms) the Spring Integration samples
|
||||
repository using the Git command line tool, issue the following commands:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[$ git clone https://github.com/SpringSource/spring-integration-samples.git]]></programlisting>
|
||||
|
||||
<para>
|
||||
That is all you need to do in order to clone the entire samples repository
|
||||
into a directory named <emphasis>spring-integration-samples</emphasis> within
|
||||
the working directory where you issued that <emphasis>git</emphasis> command.
|
||||
Since the samples repository is a live repository, you might want to perform
|
||||
periodic <emphasis>pulls</emphasis> (updates) to get new samples, as well as updates to
|
||||
the existing samples. In order to do so issue the following git
|
||||
<emphasis>PULL</emphasis> command:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[$ git pull]]></programlisting>
|
||||
|
||||
</section>
|
||||
<section>
|
||||
<title>Submitting Samples or Sample Requests</title>
|
||||
<para>
|
||||
<emphasis>How can I contribute my own Samples?</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
Github is for social coding: if you want to submit your own code examples
|
||||
to the Spring Integration Samples project, we encourage contributions
|
||||
through <ulink url="http://help.github.com/send-pull-requests/"><emphasis>pull
|
||||
requests</emphasis></ulink> from
|
||||
<ulink url="http://help.github.com/fork-a-repo/"><emphasis>forks</emphasis></ulink>
|
||||
of this repository. If you want to contribute code this way, please
|
||||
reference, if possible, a
|
||||
<ulink url="https://jira.springframework.org/browse/INTSAMPLES"><emphasis>JIRA Ticket</emphasis></ulink>
|
||||
that provides some details regarding the provided sample.
|
||||
</para>
|
||||
<important>
|
||||
<title>Sign the contributor license agreement</title>
|
||||
<para>
|
||||
Very important: before we can accept your Spring Integration sample,
|
||||
we will need you to sign the SpringSource contributor license agreement (CLA).
|
||||
Signing the contributor's agreement does not grant anyone commit rights
|
||||
to the main repository, but it does mean that we can accept your
|
||||
contributions, and you will get an author credit if we do. In order to
|
||||
read and sign the CLA, please go to:
|
||||
</para>
|
||||
<para>
|
||||
<ulink url="https://support.springsource.com/spring_committer_signup"/>
|
||||
</para>
|
||||
<para>
|
||||
As Project, please select <emphasis>Spring Integration</emphasis>.
|
||||
The Project Lead is <emphasis>Mark Fisher</emphasis>.
|
||||
</para>
|
||||
</important>
|
||||
<para><emphasis>Code Contribution Process</emphasis></para>
|
||||
<para>
|
||||
For the actual code contribution process, please read the the
|
||||
<emphasis>Contributor Guidelines</emphasis> for Spring Integration,
|
||||
they apply for this project as well:
|
||||
</para>
|
||||
<para>
|
||||
<ulink url="https://github.com/SpringSource/spring-integration/wiki/Contributor-Guidelines"/>
|
||||
</para>
|
||||
<para>
|
||||
This process ensures that every commit gets peer-reviewed. As a matter of
|
||||
fact, the core committers follow the exact same rules.
|
||||
We are gratefully looking forward to your Spring Integration Samples!
|
||||
</para>
|
||||
|
||||
<para><emphasis>Sample Requests</emphasis></para>
|
||||
|
||||
<para>
|
||||
As mentioned earlier, the <emphasis>Spring Integration Samples</emphasis>
|
||||
project has a dedicated JIRA Issue tracking system. To submit new sample
|
||||
requests, please visit our JIRA Issue Tracking system:
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<ulink url="https://jira.springframework.org/browse/INTSAMPLES">https://jira.springframework.org/browse/INTSAMPLES</ulink>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="samples-structure">
|
||||
<title>Samples Structure</title>
|
||||
<para>
|
||||
Starting with Spring Integration 2.0, the structure of the <emphasis>samples</emphasis>
|
||||
changed as well. With plans for more samples we realized that some
|
||||
samples have different goals than others. While they all share the common goal of showing you how to apply and work with
|
||||
the Spring Integration framework, they also differ in areas where some samples are meant to concentrate on a technical
|
||||
use case while others focus on a business use case, and some samples are all about showcasing various techniques that
|
||||
could be applied to address certain scenarios (both technical and business). The new categorization of samples will allow us
|
||||
to better organize them based on the problem each sample addresses while giving you a simpler way of finding the right sample
|
||||
for your needs.
|
||||
</para>
|
||||
<para>
|
||||
Currently there are 4 categories. Within the samples repository each category has its own directory which is named after the
|
||||
category name:
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>BASIC (samples/basic)</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
This is a good place to get started. The samples here are technically motivated and demonstrate the bare
|
||||
minimum with regard to configuration and code. These should help you to get started quickly by introducing you to the basic concepts,
|
||||
API and configuration of Spring Integration as well as Enterprise Integration Patterns (EIP). For example, if you are
|
||||
looking for an answer on how to implement and wire a <emphasis>Service Activator</emphasis> to a <emphasis>Message Channel</emphasis>
|
||||
or how to use a <emphasis>Messaging Gateway</emphasis> as a facade to your message exchange, or how to get started with using MAIL or
|
||||
TCP/UDP modules etc., this would be the right place to find a good sample. The bottom line is this is a good place
|
||||
to get started.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>INTERMEDIATE (samples/intermediate)</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
This category targets developers who are already familiar with the Spring Integration framework (past getting started),
|
||||
but need some more guidance while resolving the more advanced technical problems one might deal with
|
||||
after switching to a Messaging architecture.
|
||||
For example, if you are looking for an answer on how to handle errors in various message exchange
|
||||
scenarios or how to properly configure the <emphasis>Aggregator</emphasis> for the situations where some messages
|
||||
might not ever arrive for aggregation, or any other issue that goes beyond a basic implementation and configuration
|
||||
of a particular component and addresses <emphasis>what else</emphasis> types of problems, this
|
||||
would be the right place to find these type of samples.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>ADVANCED (samples/advanced)</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
This category targets developers who are very familiar with the Spring Integration framework but are looking to
|
||||
extend it to address a specific custom need by using Spring Integration's public API.
|
||||
For example, if you are looking for samples showing you how to implement a custom <emphasis>Channel</emphasis> or
|
||||
<emphasis>Consumer</emphasis> (event-based or polling-based), or you are trying to figure out what is the most appropriate
|
||||
way to implement a custom Bean parser on top of the Spring Integration Bean parser hierarchy when implementing your own
|
||||
namespace and schema for a custom component, this would be the right place to look.
|
||||
Here you can also find samples that will help you with <emphasis>Adapter</emphasis> development. Spring Integration comes
|
||||
with an extensive library of adapters to allow you to connect remote systems with the Spring Integration messaging framework.
|
||||
However you might have a need to integrate with a system for which the core framework does not provide an adapter.
|
||||
So, you may decide to implement your own (and potentially contribute it). This category would include samples showing you how.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>APPLICATIONS (samples/applications)</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
This category targets developers and architects who have a good understanding of Message-driven architecture and
|
||||
EIP, and an above average understanding of Spring and Spring Integration who are looking for samples that
|
||||
address a particular <emphasis>business problem</emphasis>. In other words the emphasis of samples in this category
|
||||
is <emphasis>business use cases</emphasis> and how they can be solved with a Message-Driven Architecture and Spring Integration
|
||||
in particular.
|
||||
For example, if you are interested to see how a <emphasis>Loan Broker</emphasis> or <emphasis>Travel Agent</emphasis>
|
||||
process could be implemented and automated via Spring Integration, this would be the right place to find these types of samples.
|
||||
</para>
|
||||
|
||||
<important>
|
||||
<remark>
|
||||
Remember: Spring Integration is a community driven framework, therefore community participation is IMPORTANT.
|
||||
That includes Samples; so, if you can't find what you are looking for, let us know!
|
||||
</remark>
|
||||
</important>
|
||||
</section>
|
||||
<section id="samples-impl">
|
||||
<title>Samples</title>
|
||||
<para>
|
||||
Currently Spring Integration comes with quite a few samples and you can only expect more.
|
||||
To help you better navigate through them, each sample comes with its own <code>readme.txt</code> file which covers
|
||||
several details about the sample (e.g., what EIP patterns it addresses, what problem it is trying to solve, how to run sample etc.).
|
||||
However, certain samples require a more detailed and sometimes graphical explanation. In this section you'll
|
||||
find details on samples that we believe require special attention.
|
||||
</para>
|
||||
<section id="samples-loan-broker">
|
||||
<title>Loan Broker</title>
|
||||
<para>
|
||||
In this section, we will review the <emphasis>Loan Broker</emphasis> sample application that is included in the
|
||||
Spring Integration samples. This sample is inspired by one of the samples featured in Gregor
|
||||
Hohpe and Bobby Woolf's book, <ulink url="http://www.eaipatterns.com">Enterprise Integration Patterns</ulink>.
|
||||
</para>
|
||||
<para>The diagram below represents the entire process</para>
|
||||
<para>
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/loan-broker-eip.png" format="PNG" align="center" scalefit="1" width="100%" contentdepth="100%" />
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/loan-broker-eip.png" format="PNG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
<para>Now lets look at this process in more detail</para>
|
||||
<para>
|
||||
At the core of an EIP architecture are the very simple yet powerful concepts of Pipes and Filters, and of course: Messages.
|
||||
Endpoints (Filters) are connected with one another via Channels (Pipes). The producing endpoint sends Message to the Channel,
|
||||
and the Message is retrieved
|
||||
by the Consuming endpoint. This architecture is meant to define various mechanisms that describe HOW information is exchanged between
|
||||
the endpoints, without any awareness of WHAT those endpoints are or what information they are exchanging. Thus, it provides for a very loosely
|
||||
coupled and flexible collaboration model while also decoupling Integration concerns from Business concerns. EIP extends this architecture
|
||||
by further defining:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>The types of pipes (Point-to-Point Channel, Publish-Subscribe Channel, Channel Adapter, etc.)</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>The core filters and patterns around how filters collaborate with pipes
|
||||
(Message Router, Splitters and Aggregators, various Message Transformation patterns, etc.)</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
The details and variations of this use case are very nicely described in Chapter 9 of the EIP Book, but here is the brief summary;
|
||||
A Consumer while shopping for the best Loan Quote(s) subscribes to the services of a Loan Broker, which handles details such as:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>Consumer pre-screening (e.g., obtain and review the consumer's Credit history)</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>Determine the most appropriate Banks (e.g., based on consumer's credit history/score)</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>Send a Loan quote request to each selected Bank</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Collect responses from each Bank</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Filter responses and determine the best quote(s), based on consumer's requirements.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Pass the Loan quote(s) back to the consumer.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
Obviously the real process of obtaining a loan quote is a bit more complex, but since our goal here is to demonstrate how
|
||||
Enterprise Integration Patterns are realized and implemented within SI, the use case has been simplified to concentrate only on
|
||||
the Integration aspects of the process. It is not an attempt to give you an advice in consumer finances.
|
||||
</para>
|
||||
<para>
|
||||
As you can see, by hiring a Loan Broker, the consumer is isolated from the details of the Loan Broker's operations, and each Loan Broker's
|
||||
operations may defer from one another to maintain competitive advantage, so whatever we assemble/implement must be flexible so any changes
|
||||
could be introduced quickly and painlessly.
|
||||
Speaking of change, the Loan Broker sample does not actually talk to any 'imaginary' Banks or Credit bureaus. Those services are stubbed out.
|
||||
Our goal here is to assemble, orchestrate and test the integration aspect of the process as a whole. Only then can we start thinking about
|
||||
wiring such process to the real services. At that time the assembled process and its configuration will not change regardless of the number
|
||||
of Banks a particular Loan Broker is dealing with, or the type of communication media (or protocols) used (JMS, WS, TCP, etc.)
|
||||
to communicate with these Banks.
|
||||
</para>
|
||||
<para> <emphasis>DESIGN</emphasis> </para>
|
||||
<para>
|
||||
As you analyze the 6 requirements above you'll quickly see that they all fall into the category of Integration concerns.
|
||||
For example, in the consumer pre-screening step we need to gather additional information about the consumer and the consumer's desires
|
||||
and enrich the loan request with additional meta information. We then have to filter such information to select the most appropriate list of
|
||||
Banks, and so on. Enrich, filter, select – these are all integration concerns for which EIP defines a solution in the form of patterns.
|
||||
SI provides an implementation of these patterns.
|
||||
</para>
|
||||
<para><emphasis>Messaging Gateway</emphasis>
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/gateway.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/gateway.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
<para>
|
||||
The <emphasis>Messaging Gateway</emphasis> pattern provides a simple mechanism to access messaging systems, including our Loan Broker.
|
||||
In SI you define the <emphasis>Gateway</emphasis> as a Plain Old Java Interface (no need to provide an implementation), configure it via the
|
||||
XML <emphasis><gateway></emphasis> element or via annotation and use it as any other Spring bean. SI will take care of
|
||||
delegating and mapping method invocations to the Messaging infrastructure by generating a <emphasis>Message</emphasis> (payload is mapped to an
|
||||
input parameter of the method) and sending it to the designated channel.
|
||||
<programlisting language="xml"><![CDATA[<int:gateway id="loanBrokerGateway"
|
||||
default-request-channel="loanBrokerPreProcessingChannel"
|
||||
service-interface="org.springframework.integration.samples.loanbroker.LoanBrokerGateway">
|
||||
<int:method name="getBestLoanQuote">
|
||||
<int:header name="RESPONSE_TYPE" value="BEST"/>
|
||||
</int:method>
|
||||
</int:gateway>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Our current <emphasis>Gateway</emphasis> provides two methods that could be invoked. One that will return the best single quote and another one that
|
||||
will return all quotes. Somehow downstream we need to know what type of reply the caller is looking for. The best way to achieve
|
||||
this in Messaging architecture is to enrich the content of the message with some meta-data describing your intentions.
|
||||
<emphasis>Content Enricher</emphasis> is one of the patterns that addresses this and although Spring Integration does provide a
|
||||
separate configuration element to enrich Message Headers with arbitrary data (we'll see it later), as a convenience, since
|
||||
<emphasis>Gateway</emphasis> element is responsible to construct the initial <emphasis>Message</emphasis> it provides embedded
|
||||
capability to enrich the newly created <emphasis>Message</emphasis> with arbitrary <emphasis>Message Headers</emphasis>. In our
|
||||
example we are adding header RESPONSE_TYPE with value 'BEST'' whenever the getBestQuote() method is invoked. For other method
|
||||
we are not adding any header. Now we can check downstream for an existence of this header and based on its presence and its value
|
||||
we can determine what type of reply the caller is looking for.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Based on the use case we also know there are some pre-screening steps that needs to be performed such as getting and evaluating the consumer's
|
||||
credit score, simply because some premiere Banks will only typically accept quote requests from consumers that meet a minimum credit
|
||||
score requirement. So it would be nice if the <emphasis>Message</emphasis> would be enriched with such information before it is forwarded
|
||||
to the Banks. It would also be nice if when several processes needs to be completed to provide such meta-information, those
|
||||
processes could be grouped in a single unit. In our use case we need to determine credit score and based on the credit score and some
|
||||
rule select a list of <emphasis>Message Channels</emphasis> (Bank Channels) we will sent quote request to.
|
||||
</para>
|
||||
<para><emphasis>Composed Message Processor</emphasis> </para>
|
||||
<para>
|
||||
The <emphasis>Composed Message Processor</emphasis> pattern describes rules around building endpoints that maintain control over message flow which
|
||||
consists of multiple message processors. In Spring Integration <emphasis>Composed Message Processor</emphasis> pattern is implemented via
|
||||
<emphasis><chain></emphasis> element.
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/chain.png" format="PNG" align="center"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/chain.png" format="PNG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
<para>
|
||||
As you can see from the above configuration we have a chain with inner header-enricher element which will further enrich the
|
||||
content of the <emphasis>Message</emphasis> with the header CREDIT_SCORE and value that will be determined by the call to a
|
||||
credit service (simple POJO spring bean identified by 'creditBureau' name) and then it will delegate to the <emphasis>Message Router</emphasis>
|
||||
</para>
|
||||
<para><emphasis>Message Router</emphasis>
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/bank-router.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/bank-router.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
<para>
|
||||
There are several implementations of the <emphasis>Message Routing</emphasis> pattern available in Spring Integration. Here we are using a
|
||||
router that will determine a list of channels based on evaluating an expression (Spring Expression Language) which will look at
|
||||
the credit score that was determined is the previous step and will select the list of channels from the Map bean with id 'banks'
|
||||
whose values are 'premier' or 'secondary' based o the value of credit score. Once the list of <emphasis>Channels</emphasis> is selected, the
|
||||
<emphasis>Message</emphasis> will be routed to those <emphasis>Channels</emphasis>.
|
||||
</para>
|
||||
<para>
|
||||
Now, one last thing the Loan Broker needs to to is to receive the loan quotes form the banks, aggregate them by consumer
|
||||
(we don't want to show quotes from one consumer to another), assemble the response based on the consumer's selection criteria
|
||||
(single best quote or all quotes) and reply back to the consumer.
|
||||
</para>
|
||||
<para><emphasis>Message Aggregator</emphasis>
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/quotes-aggregator.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/quotes-aggregator.jpg" format="JPG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
An <emphasis>Aggregator</emphasis> pattern describes an endpoint which groups related <emphasis>Messages</emphasis> into a single
|
||||
<emphasis>Message</emphasis>. Criteria and rules can be provided to determine an aggregation and correlation strategy.
|
||||
SI provides several implementations of the <emphasis>Aggregator</emphasis> pattern as well as a convenient name-space based configuration.
|
||||
<programlisting language="xml"><![CDATA[<int:aggregator id="quotesAggregator"
|
||||
input-channel="quotesAggregationChannel"
|
||||
method="aggregateQuotes">
|
||||
<beans:bean class="org.springframework.integration.samples.loanbroker.LoanQuoteAggregator"/>
|
||||
</int:aggregator>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Our Loan Broker defines a 'quotesAggregator' bean via the <emphasis><aggregator></emphasis> element which provides a default
|
||||
aggregation and correlation strategy. The default correlation strategy correlates messages based on the <code>correlationId</code> header
|
||||
(see <emphasis>Correlation Identifier</emphasis> pattern). What's interesting is that we never provided the value for this header.
|
||||
It was set earlier by the router automatically, when it generated a separate <emphasis>Message</emphasis> for each Bank channel.
|
||||
</para>
|
||||
<para>
|
||||
Once the <emphasis>Messages</emphasis> are correlated they are released to the actual <emphasis>Aggregator</emphasis> implementation.
|
||||
Although default <emphasis>Aggregator</emphasis> is provided by SI, its strategy (gather the list of payloads from all
|
||||
<emphasis>Messages</emphasis> and construct a new <emphasis>Message</emphasis> with this List as payload) does not satisfy our
|
||||
requirement. The reason is that our consumer might require a single best quote or all quotes. To communicate the consumer's
|
||||
intention, earlier in the process we set the RESPONSE_TYPE header. Now we have to evaluate this header and return either
|
||||
all the quotes (the default aggregation strategy would work) or the best quote (the default aggregation strategy will not work
|
||||
because we have to determine which loan quote is the best).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Obviously selecting the best quote could be based on complex criteria and would influence the complexity of the aggregator implementation and
|
||||
configuration, but for now we are making it simple. If consumer wants the best quote we will select a quote with the lowest interest
|
||||
rate. To accomplish that the LoanQuoteAggregator.java will sort all the quotes and return the first one.
|
||||
The <classname>LoanQuote.java</classname> implements <interfacename>Comparable</interfacename> which compares quotes based on the rate attribute.
|
||||
Once the response <emphasis>Message</emphasis> is created it is sent to the default-reply-channel of the <emphasis>Messaging Gateway</emphasis>
|
||||
(thus the consumer) which started the process. Our consumer got the Loan Quote!
|
||||
</para>
|
||||
<para>Conclusion</para>
|
||||
<para>
|
||||
As you can see a rather complex process was assembled based on POJO (read existing, legacy), light weight, embeddable messaging
|
||||
framework (Spring Integration) with a loosely coupled programming model intended to simplify integration of heterogeneous systems
|
||||
without requiring a heavy-weight ESB-like engine or proprietary development and deployment environment, because as a developer you
|
||||
should not be porting your Swing or console-based application to an ESB-like server or implementing proprietary interfaces just
|
||||
because you have an integration concern.
|
||||
</para>
|
||||
<para>
|
||||
This and other samples in this section are built on top of Enterprise Integration Patterns and can be considered "building blocks"
|
||||
for YOUR solution; they are not intended to be complete solutions. Integration concerns exist in all types of application
|
||||
(whether server based or not).
|
||||
It should not require change in design, testing and deployment strategy if such applications need to be integrated.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="samples-cafe">
|
||||
<title>The Cafe Sample</title>
|
||||
<para>
|
||||
In this section, we will review a <emphasis>Cafe</emphasis> sample application that is included in the
|
||||
Spring Integration samples. This sample is inspired by another sample featured in Gregor
|
||||
Hohpe's <ulink url="http://www.eaipatterns.com/ramblings.html">Ramblings</ulink>.
|
||||
</para>
|
||||
<para>
|
||||
The domain is that of a Cafe, and the basic flow is depicted in the following diagram:
|
||||
</para>
|
||||
<para>
|
||||
<mediaobject>
|
||||
<imageobject role="fo">
|
||||
<imagedata fileref="images/cafe-eip.png" format="PNG" align="center" scalefit="1" width="100%" contentdepth="100%" />
|
||||
</imageobject>
|
||||
<imageobject role="html">
|
||||
<imagedata fileref="images/cafe-eip.png" format="PNG" align="center"/>
|
||||
</imageobject>
|
||||
</mediaobject>
|
||||
</para>
|
||||
<para>
|
||||
The <classname>Order</classname> object may contain multiple <classname>OrderItems</classname>. Once the order
|
||||
is placed, a <emphasis>Splitter</emphasis> will break the composite order message into a single message per
|
||||
drink. Each of these is then processed by a <emphasis>Router</emphasis> that determines whether the drink is hot
|
||||
or cold (checking the <classname>OrderItem</classname> object's 'isIced' property). The
|
||||
<classname>Barista</classname> prepares each drink, but hot and cold drink preparation are handled by two
|
||||
distinct methods: 'prepareHotDrink' and 'prepareColdDrink'. The prepared drinks are then sent to the Waiter where
|
||||
they are aggregated into a <classname>Delivery</classname> object.
|
||||
</para>
|
||||
<para>
|
||||
Here is the XML configuration:
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns:int="http://www.springframework.org/schema/integration"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd
|
||||
http://www.springframework.org/schema/integration/stream
|
||||
http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd">
|
||||
|
||||
<int:gateway id="cafe" service-interface="org.springframework.integration.samples.cafe.Cafe"/>
|
||||
|
||||
<int:channel id="orders"/>
|
||||
<int:splitter input-channel="orders" ref="orderSplitter" method="split" output-channel="drinks"/>
|
||||
|
||||
<int:channel id="drinks"/>
|
||||
<int:router input-channel="drinks" ref="drinkRouter" method="resolveOrderItemChannel"/>
|
||||
|
||||
<int:channel id="coldDrinks">
|
||||
<int:queue capacity="10"/>
|
||||
</int:channel>
|
||||
<int:service-activator input-channel="coldDrinks" ref="barista"
|
||||
method="prepareColdDrink" output-channel="preparedDrinks"/>
|
||||
|
||||
<int:channel id="hotDrinks">
|
||||
<int:queue capacity="10"/>
|
||||
</int:channel>
|
||||
<int:service-activator input-channel="hotDrinks" ref="barista"
|
||||
method="prepareHotDrink" output-channel="preparedDrinks"/>
|
||||
|
||||
<int:channel id="preparedDrinks"/>
|
||||
<int:aggregator input-channel="preparedDrinks" ref="waiter"
|
||||
method="prepareDelivery" output-channel="deliveries"/>
|
||||
|
||||
<int-stream:stdout-channel-adapter id="deliveries"/>
|
||||
|
||||
<beans:bean id="orderSplitter"
|
||||
class="org.springframework.integration.samples.cafe.xml.OrderSplitter"/>
|
||||
|
||||
<beans:bean id="drinkRouter"
|
||||
class="org.springframework.integration.samples.cafe.xml.DrinkRouter"/>
|
||||
|
||||
<beans:bean id="barista" class="org.springframework.integration.samples.cafe.xml.Barista"/>
|
||||
|
||||
<beans:bean id="waiter" class="org.springframework.integration.samples.cafe.xml.Waiter"/>
|
||||
|
||||
<int:poller id="poller" default="true" fixed-rate="1000"/>
|
||||
|
||||
</beans:beans>]]></programlisting>
|
||||
As you can see, each Message Endpoint is connected to input and/or output channels. Each endpoint will manage
|
||||
its own Lifecycle (by default endpoints start automatically upon initialization - to prevent that add the
|
||||
"auto-startup" attribute with a value of "false"). Most importantly, notice that the objects are simple POJOs
|
||||
with strongly typed method arguments. For example, here is the Splitter:
|
||||
<programlisting language="java"><![CDATA[public class OrderSplitter {
|
||||
|
||||
public List<OrderItem> split(Order order) {
|
||||
return order.getItems();
|
||||
}
|
||||
}]]></programlisting>
|
||||
In the case of the Router, the return value does not have to be a <interfacename>MessageChannel</interfacename>
|
||||
instance (although it can be). As you see in this example, a String-value representing the channel name is
|
||||
returned instead.
|
||||
<programlisting language="java"><![CDATA[public class DrinkRouter {
|
||||
|
||||
public String resolveOrderItemChannel(OrderItem orderItem) {
|
||||
return (orderItem.isIced()) ? "coldDrinks" : "hotDrinks";
|
||||
}
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Now turning back to the XML, you see that there are two <service-activator> elements. Each of these
|
||||
is delegating to the same <classname>Barista</classname> instance but different methods: 'prepareHotDrink'
|
||||
or 'prepareColdDrink' corresponding to the two channels where order items have been routed.
|
||||
<programlisting language="java"><![CDATA[public class Barista {
|
||||
|
||||
private long hotDrinkDelay = 5000;
|
||||
private long coldDrinkDelay = 1000;
|
||||
|
||||
private AtomicInteger hotDrinkCounter = new AtomicInteger();
|
||||
private AtomicInteger coldDrinkCounter = new AtomicInteger();
|
||||
|
||||
public void setHotDrinkDelay(long hotDrinkDelay) {
|
||||
this.hotDrinkDelay = hotDrinkDelay;
|
||||
}
|
||||
|
||||
public void setColdDrinkDelay(long coldDrinkDelay) {
|
||||
this.coldDrinkDelay = coldDrinkDelay;
|
||||
}
|
||||
|
||||
public Drink prepareHotDrink(OrderItem orderItem) {
|
||||
try {
|
||||
Thread.sleep(this.hotDrinkDelay);
|
||||
System.out.println(Thread.currentThread().getName()
|
||||
+ " prepared hot drink #" + hotDrinkCounter.incrementAndGet()
|
||||
+ " for order #" + orderItem.getOrder().getNumber() + ": " + orderItem);
|
||||
return new Drink(orderItem.getOrder().getNumber(), orderItem.getDrinkType(),
|
||||
orderItem.isIced(), orderItem.getShots());
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Drink prepareColdDrink(OrderItem orderItem) {
|
||||
try {
|
||||
Thread.sleep(this.coldDrinkDelay);
|
||||
System.out.println(Thread.currentThread().getName()
|
||||
+ " prepared cold drink #" + coldDrinkCounter.incrementAndGet()
|
||||
+ " for order #" + orderItem.getOrder().getNumber() + ": " + orderItem);
|
||||
return new Drink(orderItem.getOrder().getNumber(), orderItem.getDrinkType(),
|
||||
orderItem.isIced(), orderItem.getShots());
|
||||
}
|
||||
catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
As you can see from the code excerpt above, the barista methods have different delays (the hot drinks take 5
|
||||
times as long to prepare). This simulates work being completed at different rates. When the
|
||||
<classname>CafeDemo</classname> 'main' method runs, it will loop 100 times sending a single hot drink and a
|
||||
single cold drink each time. It actually sends the messages by invoking the 'placeOrder' method on the Cafe
|
||||
interface. Above, you will see that the <gateway> element is specified in the configuration file. This
|
||||
triggers the creation of a proxy that implements the given 'service-interface' and connects it to a channel.
|
||||
The channel name is provided on the @Gateway annotation of the <interfacename>Cafe</interfacename> interface.
|
||||
<programlisting language="java">public interface Cafe {
|
||||
|
||||
@Gateway(requestChannel="orders")
|
||||
void placeOrder(Order order);
|
||||
|
||||
}</programlisting>
|
||||
Finally, have a look at the <methodname>main()</methodname> method of the <classname>CafeDemo</classname> itself.
|
||||
<programlisting language="java"><![CDATA[public static void main(String[] args) {
|
||||
AbstractApplicationContext context = null;
|
||||
if (args.length > 0) {
|
||||
context = new FileSystemXmlApplicationContext(args);
|
||||
}
|
||||
else {
|
||||
context = new ClassPathXmlApplicationContext("cafeDemo.xml", CafeDemo.class);
|
||||
}
|
||||
Cafe cafe = context.getBean("cafe", Cafe.class);
|
||||
for (int i = 1; i <= 100; i++) {
|
||||
Order order = new Order(i);
|
||||
order.addItem(DrinkType.LATTE, 2, false);
|
||||
order.addItem(DrinkType.MOCHA, 3, true);
|
||||
cafe.placeOrder(order);
|
||||
}
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
<tip>
|
||||
To run this sample as well as 8 others, refer to the <code>README.txt</code> within the "samples" directory
|
||||
of the main distribution as described at the beginning of this chapter.
|
||||
</tip>
|
||||
<para>
|
||||
When you run cafeDemo, you will see that the cold drinks are initially prepared more quickly than the hot drinks.
|
||||
Because there is an aggregator, the cold drinks are effectively limited by the rate of the hot drink preparation.
|
||||
This is to be expected based on their respective delays of 1000 and 5000 milliseconds. However, by configuring a
|
||||
poller with a concurrent task executor, you can dramatically change the results. For example, you could use a
|
||||
thread pool executor with 5 workers for the hot drink barista while keeping the cold drink barista as it is:
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="hotDrinks"
|
||||
ref="barista"
|
||||
method="prepareHotDrink"
|
||||
output-channel="preparedDrinks"/>
|
||||
|
||||
<int:service-activator input-channel="hotDrinks"
|
||||
ref="barista"
|
||||
method="prepareHotDrink"
|
||||
output-channel="preparedDrinks">
|
||||
]]><emphasis><![CDATA[<int:poller task-executor="pool" fixed-rate="1000"/>
|
||||
]]></emphasis><![CDATA[
|
||||
</int:service-activator>
|
||||
|
||||
]]><emphasis><![CDATA[<task:executor id="pool" pool-size="5"/>]]></emphasis></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Also, notice that the worker thread name is displayed with each invocation. You will see that the hot drinks are
|
||||
prepared by the task-executor threads. If you provide a much shorter poller interval (such as 100 milliseconds),
|
||||
then you will notice that occasionally it throttles the input by forcing the task-scheduler (the caller) to invoke
|
||||
the operation.
|
||||
</para>
|
||||
<note>
|
||||
In addition to experimenting with the poller's concurrency settings, you can also add the 'transactional'
|
||||
sub-element and then refer to any PlatformTransactionManager instance within the context.
|
||||
</note>
|
||||
</section>
|
||||
|
||||
<section id="samples-xml-messaging">
|
||||
<title>The XML Messaging Sample</title>
|
||||
<para>
|
||||
The xml messaging sample in the <package>org.springframework.integration.samples.xml</package> illustrates how to use
|
||||
some of the provided components which deal with xml payloads. The sample uses the idea of processing an order for books
|
||||
represented as xml.
|
||||
</para>
|
||||
<para>
|
||||
First the order is split into a number of messages, each one representing a single order item using
|
||||
the XPath splitter component.
|
||||
<programlisting language="xml"><![CDATA[<int-xml:xpath-splitter id="orderItemSplitter" input-channel="ordersChannel"
|
||||
output-channel="stockCheckerChannel" create-documents="true">
|
||||
<int-xml:xpath-expression expression="/orderNs:order/orderNs:orderItem"
|
||||
namespace-map="orderNamespaceMap" />
|
||||
</int-xml:xpath-splitter>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
A service activator is then used to pass the message into a stock checker POJO. The order item document is enriched with information
|
||||
from the stock checker about order item stock level. This enriched order item message is then used to route the message. In the
|
||||
case where the order item is in stock the message is routed to the warehouse.
|
||||
<programlisting language="xml"><![CDATA[<si-xml:xpath-router id="instockRouter" input-channel="orderRoutingChannel" resolution-required="true">
|
||||
<si-xml:xpath-expression expression="/orderNs:orderItem/@in-stock" namespace-map="orderNamespaceMap" />
|
||||
<si-xml:mapping value="true" channel="warehouseDispatchChannel"/>
|
||||
<si-xml:mapping value="false" channel="outOfStockChannel"/>
|
||||
</si-xml:xpath-router>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Where the order item is not in stock the message is transformed using
|
||||
xslt into a format suitable for sending to the supplier.
|
||||
<programlisting language="xml"><![CDATA[<int-xml:xslt-transformer input-channel="outOfStockChannel"
|
||||
output-channel="resupplyOrderChannel"
|
||||
xsl-resource="classpath:org/springframework/integration/samples/xml/bigBooksSupplierTransformer.xsl"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
</appendix>
|
||||
126
src/reference/docbook/scripting.xml
Normal file
@@ -0,0 +1,126 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section version="5.0" xml:id="scripting" xmlns="http://docbook.org/ns/docbook"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink"
|
||||
xmlns:ns5="http://www.w3.org/1999/xhtml"
|
||||
xmlns:ns4="http://www.w3.org/1998/Math/MathML"
|
||||
xmlns:ns3="http://www.w3.org/2000/svg"
|
||||
xmlns:ns="http://docbook.org/ns/docbook">
|
||||
<title>Scripting support</title>
|
||||
|
||||
<para>With Spring Integration 2.1 we've added support for the <ulink url="http://jcp.org/aboutJava/communityprocess/pr/jsr223/">
|
||||
JSR223 Scripting for Java specification</ulink>,
|
||||
introduced in Java version 6. This allows you to use scripts written in any supported language including
|
||||
Ruby/JRuby, Javascript and Groovy to provide the logic for various integration components similar to the way
|
||||
the Spring Expression Language (SpEL) is used in Spring Integration. For more information about JSR223 please refer to the
|
||||
<ulink url="http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/">documentation</ulink>
|
||||
<important>
|
||||
Note that this feature requires Java 6 or higher. Sun developed a JSR223 reference implementation which works with
|
||||
Java 5 but it is not officially supported and we have not tested it with Spring Integration.
|
||||
</important>
|
||||
</para>
|
||||
<para>
|
||||
In order to use a JVM scripting language, a JSR223 implementation for that language must be included in your class path. Java 6 natively
|
||||
supports Javascript. The <ulink url="http://groovy.codehaus.org">Groovy</ulink> and
|
||||
<ulink url="http://jruby.org/">JRuby</ulink> projects provide JSR233 support in their standard distribution.
|
||||
Other language implementations may be available or under development. Please refer to the appropriate project website for more information.
|
||||
<important>
|
||||
Various JSR223 language implementations have been developed by third parties. A particular implementation's compatibility
|
||||
with Spring Integration depends on how well it conforms to the specification and/or the implementer's interpretation of the specification.
|
||||
</important>
|
||||
<tip>If you plan to use Groovy as your scripting language, we recommended you use <xref linkend="groovy">Spring-Integration's Groovy Support</xref>
|
||||
as it offers additional features specific to Groovy. <emphasis>However you will find this section relevant as well</emphasis>.
|
||||
</tip>
|
||||
</para>
|
||||
|
||||
<section id="scripting-config">
|
||||
<title>Script configuration</title>
|
||||
|
||||
<para>Depending on the complexity of your integration requirements
|
||||
scripts may be provided inline as CDATA in XML configuration or as a
|
||||
reference to a Spring resource containing the script. To enable scripting support
|
||||
Spring Integration defines a
|
||||
<classname>ScriptExecutingMessageProcessor</classname> which will
|
||||
bind the Message Payload to a
|
||||
variable named <code>payload</code> and the Message Headers to a <code>headers</code>
|
||||
variable, both accessible within the script execution context. All that is left for you to do is
|
||||
write a script that uses these variables. Below are a couple of sample configurations:</para>
|
||||
|
||||
<para><emphasis>Filter</emphasis> <programlisting language="xml"><int:filter input-channel="referencedScriptInput">
|
||||
<int-script:script lang="ruby" location="some/path/to/ruby/script/RubyFilterTests.rb"/>
|
||||
</int:filter>
|
||||
|
||||
<int:filter input-channel="inlineScriptInput">
|
||||
<int-script:script lang="groovy"><![CDATA[
|
||||
return payload == 'good'
|
||||
]]></int-script:script>
|
||||
</int:filter></programlisting>
|
||||
|
||||
Here, you see that the script can be included inline
|
||||
or can reference a resource location via the <code>location</code> attribute. Additionally the <code>lang</code> attribute
|
||||
corresponds to the language name (or JSR223 alias)</para>
|
||||
|
||||
<para>Other Spring Integration endpoint elements which support scripting include <emphasis>router</emphasis>, <emphasis>service-activator</emphasis>,
|
||||
<emphasis>transformer</emphasis>, and <emphasis>splitter</emphasis>. The scripting configuration in each case would be identical to the above
|
||||
(besides the endpoint element).
|
||||
</para>
|
||||
|
||||
<para>Another useful feature of Scripting support is the ability to update (reload) scripts without
|
||||
having to restart the Application Context. To accomplish this, specify the <code>refresh-check-delay</code>
|
||||
attribute on the <emphasis>script</emphasis> element:
|
||||
|
||||
<programlisting language="xml"><int-script:script location="..." refresh-check-delay="5000"/></programlisting>
|
||||
|
||||
In the above example, the script location will be checked for updates every 5 seconds. If the script is updated,
|
||||
any invocation that occurs later than 5 seconds since the update will result in execution of the new script.
|
||||
|
||||
<programlisting language="xml"><int-script:script location="..." refresh-check-delay="0"/></programlisting>
|
||||
|
||||
In the above example the context will be updated with any script modifications
|
||||
as soon as such modification occurs, providing a simple mechanism for 'real-time' configuration.
|
||||
|
||||
Any negative number value means the script will not be reloaded after initialization of the application context.
|
||||
This is the default behavior. <important>Inline scripts can not be reloaded.</important></para>
|
||||
|
||||
<programlisting language="xml"><int-script:script location="..." refresh-check-delay="-1"/></programlisting>
|
||||
|
||||
<para><emphasis>Script variable bindings</emphasis> </para>
|
||||
|
||||
<para>
|
||||
Variable bindings are required to enable the script to reference variables externally provided to the script's execution context.
|
||||
As we have seen, <code>payload</code> and <code>headers</code> are used as binding variables by default. You can bind additional variables
|
||||
to a script via <code><variable></code> sub-elements:
|
||||
<programlisting language="xml"><![CDATA[<script:script lang="js" location="foo/bar/MyScript.js">
|
||||
<script:variable name="foo" value="foo"/>
|
||||
<script:variable name="bar" value="bar"/>
|
||||
<script:variable name="date" ref="date"/>
|
||||
</script:script>]]></programlisting>
|
||||
As shown in the above example, you can bind a script variable either to a scalar value or a Spring bean reference. Note that
|
||||
<code>payload</code> and <code>headers</code> will still be included as binding variables.
|
||||
|
||||
</para>
|
||||
<para>
|
||||
If you need more control over how variables are generated, you can implement your own Java class
|
||||
using the <classname>ScriptVariableGenerator</classname> strategy:
|
||||
<programlisting language="java"><![CDATA[public interface ScriptVariableGenerator {
|
||||
|
||||
Map<String, Object> generateScriptVariables(Message<?> message);
|
||||
|
||||
}]]></programlisting>
|
||||
|
||||
This interface requires you to implement the method <code>generateScriptVariables(Message)</code>. The Message
|
||||
argument allows you to access any data available in the Message payload and headers and the return value is
|
||||
the Map of bound variables. This method will be called every time the script is executed for a Message. All you need to do is
|
||||
provide an implementation of <classname>ScriptVariableGenerator</classname> and reference it with the <code>script-variable-generator</code>
|
||||
attribute:
|
||||
<programlisting language="xml"><![CDATA[<int-script:script location="foo/bar/MyScript.groovy"
|
||||
script-variable-generator="variableGenerator"/>
|
||||
|
||||
<bean id="variableGenerator" class="foo.bar.MyScriptVariableGenerator"/>]]></programlisting>
|
||||
|
||||
<important>
|
||||
You cannot provide both the <code>script-variable-generator</code> attribute and <code><variable></code> sub-element(s)
|
||||
as they are mutually exclusive. Also, custom variable bindings cannot be used with an inline script.
|
||||
</important>
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
64
src/reference/docbook/security.xml
Normal file
@@ -0,0 +1,64 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="security"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Security in Spring Integration</title>
|
||||
|
||||
<section id="security-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
Spring Integration builds upon the
|
||||
<ulink url="http://static.springframework.org/spring-security/site/">Spring Security project</ulink>
|
||||
to enable role based security checks to be applied to channel send and receive invocations.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="securing-channels">
|
||||
<title>Securing channels</title>
|
||||
<para>
|
||||
Spring Integration provides the interceptor <classname>ChannelSecurityInterceptor</classname>, which extends
|
||||
<classname>AbstractSecurityInterceptor</classname> and intercepts send and receive calls on the channel. Access decisions
|
||||
are then made with reference to a <classname>ChannelSecurityMetadataSource</classname> which provides the metadata describing
|
||||
the send and receive access policies for certain channels. The interceptor requires that a valid <interfacename>SecurityContext</interfacename>
|
||||
has been established by authenticating with Spring Security. See the Spring Security reference documentation for details.
|
||||
</para>
|
||||
<para>
|
||||
Namespace support is provided to allow easy configuration of security constraints. This consists of the secured channels tag which allows
|
||||
definition of one or more channel name patterns in conjunction with a definition of the security configuration for send and receive. The pattern
|
||||
is a <interfacename>java.util.regexp.Pattern</interfacename>.
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns:int="http://www.springframework.org/schema/integration"
|
||||
xmlns:int-security="http://www.springframework.org/schema/integration/security"
|
||||
xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:security="http://www.springframework.org/schema/security"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd
|
||||
http://www.springframework.org/schema/integration/security
|
||||
http://www.springframework.org/schema/integration/security/spring-integration-security.xsd">
|
||||
|
||||
<int-security:secured-channels>
|
||||
<int-security:access-policy pattern="admin.*" send-access="ROLE_ADMIN"/>
|
||||
<int-security:access-policy pattern="user.*" receive-access="ROLE_USER"/>
|
||||
</int-security:secured-channels>]]>
|
||||
</programlisting>
|
||||
|
||||
By default the secured-channels namespace element expects a bean named <emphasis>authenticationManager</emphasis> which implements
|
||||
<interfacename>AuthenticationManager</interfacename> and a bean named <emphasis>accessDecisionManager</emphasis> which implements
|
||||
<interfacename>AccessDecisionManager</interfacename>. Where this is not the case references to the appropriate beans can be configured
|
||||
as attributes of the <emphasis>secured-channels</emphasis> element as below.
|
||||
<programlisting language="xml"><![CDATA[<int-security:secured-channels access-decision-manager="customAccessDecisionManager"
|
||||
authentication-manager="customAuthenticationManager">
|
||||
<int-security:access-policy pattern="admin.*" send-access="ROLE_ADMIN"/>
|
||||
<int-security:access-policy pattern="user.*" receive-access="ROLE_USER"/>
|
||||
</int-security:secured-channels>]]>
|
||||
</programlisting>
|
||||
|
||||
</para>
|
||||
</section>
|
||||
|
||||
|
||||
</chapter>
|
||||
102
src/reference/docbook/service-activator.xml
Normal file
@@ -0,0 +1,102 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="service-activator"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Service Activator</title>
|
||||
|
||||
<section id="service-activator-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
The Service Activator is the endpoint type for connecting any Spring-managed Object to an input channel so that
|
||||
it may play the role of a service. If the service produces output, it may also be connected to an output channel.
|
||||
Alternatively, an output producing service may be located at the end of a processing pipeline or message flow in
|
||||
which case, the inbound Message's "replyChannel" header can be used. This is the default behavior if no output
|
||||
channel is defined, and as with most of the configuration options you'll see here, the same behavior actually
|
||||
applies for most of the other components we have seen.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="service-activator-namespace">
|
||||
<title>Configuring Service Activator</title>
|
||||
<para>
|
||||
To create a Service Activator, use the 'service-activator' element with the 'input-channel' and 'ref' attributes:
|
||||
<programlisting language="xml"><int:service-activator input-channel="exampleChannel" ref="exampleHandler"/></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The configuration above assumes that "exampleHandler" either contains a single method annotated with the
|
||||
@ServiceActivator annotation or that it contains only one public method at all. To delegate to an explicitly
|
||||
defined method of any object, simply add the "method" attribute.
|
||||
<programlisting language="xml"><int:service-activator input-channel="exampleChannel" ref="somePojo" method="someMethod"/></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
In either case, when the service method returns a non-null value, the endpoint will attempt to send the reply
|
||||
message to an appropriate reply channel. To determine the reply channel, it will first check if an
|
||||
"output-channel" was provided in the endpoint configuration:
|
||||
<programlisting language="xml"><int:service-activator input-channel="exampleChannel" output-channel="replyChannel"
|
||||
ref="somePojo" method="someMethod"/></programlisting>
|
||||
If no "output-channel" is available, it will then check the Message's <literal>replyChannel</literal> header
|
||||
value. If that value is available, it will then check its type. If it is a
|
||||
<interfacename>MessageChannel</interfacename>, the reply message will be sent to that channel. If it is a
|
||||
<classname>String</classname>, then the endpoint will attempt to resolve the channel name to a channel instance.
|
||||
If the channel cannot be resolved, then a <classname>ChannelResolutionException</classname> will be thrown.
|
||||
It it can be resolved, the Message will be sent there. This is the technique used for Request Reply messaging
|
||||
in Spring Integration, and it is also an example of the Return Address pattern.
|
||||
</para>
|
||||
<para>
|
||||
The argument in the service method could be either a Message or an arbitrary type. If the latter, then it will
|
||||
be assumed that it is a Message payload, which will be extracted from the message and injected into such service
|
||||
method. This is generally the recommended approach as it follows and promotes a POJO model when working with Spring
|
||||
Integration. Arguments may also have @Header or @Headers annotations as described in <xref linkend="annotations"/>
|
||||
</para>
|
||||
<note>
|
||||
The service method is not required to have any arguments at all, which means you
|
||||
can implement event-style Service Activators, where all you care about is an invocation of the service method,
|
||||
not worrying about the contents of the message. Think of it as a NULL JMS message. An example use-case for such an
|
||||
implementation could be a simple counter/monitor of messages deposited on the input channel.
|
||||
</note>
|
||||
<para>
|
||||
Using a "ref" attribute is generally recommended if the custom Service Activator handler implementation can be reused
|
||||
in other <code><service-activator></code> definitions. However if the custom Service Activator handler implementation
|
||||
is only used within a single definition of the <code><service-activator></code>, you can provide an inner bean definition:
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator id="exampleServiceActivator" input-channel="inChannel"
|
||||
output-channel = "outChannel" method="foo">
|
||||
<beans:bean class="org.foo.ExampleServiceActivator"/>
|
||||
</int:service-activator>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
Using both the "ref" attribute and an inner handler definition in the same <code><service-activator></code>
|
||||
configuration is not allowed, as it creates an ambiguous condition and will result in an Exception being thrown.
|
||||
</para>
|
||||
</note>
|
||||
|
||||
<para>
|
||||
<emphasis>Service Activators and the Spring Expression Language (SpEL)</emphasis>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Since Spring Integration 2.0, Service Activators can also benefit from SpEL
|
||||
(http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html).
|
||||
</para>
|
||||
<para>
|
||||
For example, you may now invoke any bean method without pointing to the bean via a <code>ref</code> attribute or including it as an
|
||||
inner bean definition. For example:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="in" output-channel="out"
|
||||
expression="@accountService.processAccount(payload, headers.accountId)"/>
|
||||
|
||||
<bean id="accountService" class="foo.bar.Account"/>]]></programlisting>
|
||||
|
||||
In the above configuration instead of injecting 'accountService' using a <code>ref</code> or as an inner bean,
|
||||
we are simply using SpEL's <code>@beanId</code> notation and invoking a method which takes a type compatible with Message payload. We
|
||||
are also passing a header value. As you can see, any valid SpEL expression can be evaluated against any content in the Message.
|
||||
For simple scenarios your <emphasis>Service Activators</emphasis> do not even have to reference a bean if all logic can be encapsulated
|
||||
by such an expression.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:service-activator input-channel="in" output-channel="out" expression="payload * 2"/>]]></programlisting>
|
||||
In the above configuration our service logic is to simply multiply the payload value by 2, and SpEL lets us handle it relatively easy.
|
||||
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
</section>
|
||||
323
src/reference/docbook/sftp.xml
Normal file
@@ -0,0 +1,323 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="sftp"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>SFTP Adapters</title>
|
||||
<para>
|
||||
Spring Integration provides support for file transfer operations via SFTP.
|
||||
</para>
|
||||
<section id="sftp-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
The Secure File Transfer Protocol (SFTP) is a network protocol which allows you to transfer
|
||||
files between two computers on the Internet over any reliable stream.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The SFTP protocol requires a secure channel, such as SSH, as well as visibility to a client's identity throughout the SFTP session.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration supports sending and receiving files over SFTP by providing three <emphasis>client</emphasis>
|
||||
side endpoints:
|
||||
<emphasis>Inbound Channel Adapter</emphasis>, <emphasis>Outbound Channel Adapter</emphasis>, and <emphasis>Outbound Gateway</emphasis>
|
||||
It also provides convenient
|
||||
namespace configuration to define these <emphasis>client</emphasis> components.
|
||||
|
||||
<programlisting language="xml"><![CDATA[xmlns:int-sftp="http://www.springframework.org/schema/integration/sftp"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration/sftp
|
||||
http://www.springframework.org/schema/integration/sftp/spring-integration-sftp.xsd"
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="sftp-session-factory">
|
||||
<title>SFTP Session Factory</title>
|
||||
<para>
|
||||
Before configuring SFTP adapters you must configure an <emphasis>SFTP Session Factory</emphasis>. You can configure
|
||||
the <emphasis>SFTP Session Factory</emphasis> via a regular bean definition:
|
||||
Below is a basic configuration:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<beans:bean id="sftpSessionFactory" class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
|
||||
<beans:property name="host" value="loclahost"/>
|
||||
<beans:property name="privateKey" value="classpath:META-INF/keys/sftpTest"/>
|
||||
<beans:property name="privateKeyPassphrase" value="springIntegration"/>
|
||||
<beans:property name="port" value="22"/>
|
||||
<beans:property name="user" value="kermit"/>
|
||||
</beans:bean>]]></programlisting>
|
||||
|
||||
<para>
|
||||
Every time an adapter requests a session object from its <interfacename>SessionFactory</interfacename> the session is
|
||||
returned from a session pool maintained by a caching wrapper around the factory. A Session in the session pool might go stale
|
||||
(if it has been disconnected by the server due to inactivity) so the <interfacename>SessionFactory</interfacename>
|
||||
will perform validation to make sure that it never returns a stale session to the adapter. If a stale session was encountered,
|
||||
it will be removed from the pool, and a new one will be created.
|
||||
<note>
|
||||
If you experience connectivity problems and would like to trace Session creation as well as see which Sessions are
|
||||
polled you may enable it by setting the logger to TRACE level (e.g., log4j.category.org.springframework.integration.file=TRACE)
|
||||
</note>
|
||||
</para>
|
||||
|
||||
Now all you need to do is inject this <emphasis>SFTP Session Factory</emphasis> into your adapters.
|
||||
</para>
|
||||
<para>
|
||||
<note>
|
||||
A more practical way to provide values for the <emphasis>SFTP Session Factory</emphasis> would be via Spring's property
|
||||
placeholder support (http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-placeholderconfigurer)
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="sftp-inbound">
|
||||
<title>SFTP Inbound Channel Adapter</title>
|
||||
<para>
|
||||
The <emphasis>SFTP Inbound Channel Adapter</emphasis> is a special listener that will connect to the server and listen for
|
||||
the remote directory events (e.g., new file created) at which point it will initiate a file transfer.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-sftp:inbound-channel-adapter id="sftpAdapterAutoCreate"
|
||||
session-factory="sftpSessionFactory"
|
||||
channel="requestChannel"
|
||||
filename-pattern="*.txt"
|
||||
remote-directory="/foo/bar"
|
||||
local-directory="file:target/foo"
|
||||
auto-create-local-directory="true"
|
||||
local-filename-generator-expression="#this.toUpperCase() + '.a'"
|
||||
delete-remote-files="false">
|
||||
<int:poller fixed-rate="1000"/>
|
||||
</int-sftp:inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
As you can see from the configuration above you can configure the <emphasis>SFTP Inbound Channel Adapter</emphasis> via the
|
||||
<code>inbound-channel-adapter</code> element while also providing values for various attributes such as <code>local-directory</code>
|
||||
- where files are going to be transferred TO and <code>remote-directory</code> - the remote source directory where files are
|
||||
going to be transferred FROM -
|
||||
as well as other attributes including a <code>session-factory</code> reference to the bean we configured earlier.
|
||||
</para>
|
||||
<para>
|
||||
By default the transferred file will carry the same name as the original file. If you want to override this behavior you
|
||||
can set the <code>local-filename-generator-expression</code> attribute which allows you to provide a SpEL Expression to generate
|
||||
the name of the local file. Unlike outbound gateways and adapters where the root object of the SpEL Evaluation Context
|
||||
is a <classname>Message</classname>, this inbound adapter does not yet have the Message at the time of evaluation since
|
||||
that's what it ultimately generates with the transferred file as its payload. So, the root object of the SpEL Evaluation Context
|
||||
is the original name of the remote file (String).
|
||||
</para>
|
||||
<para>
|
||||
Some times file filtering based on the simple pattern specified via <code>filename-pattern</code> attribute might not be
|
||||
sufficient. If this is the case, you can use the <code>filename-regex</code> attribute to specify a Regular Expression
|
||||
(e.g. <code>filename-regex=".*\.test$"</code>). And of course if you need complete control you can use the <code>filter</code>
|
||||
attribute to provide a reference to a custom implementation of the
|
||||
<classname>org.springframework.integration.file.filters.FileListFilter</classname> - a strategy interface for filtering a
|
||||
list of files.
|
||||
</para>
|
||||
<para>
|
||||
Please refer to the schema for more detail on these attributes.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
It is also important to understand that <emphasis>SFTP Inbound Channel Adapter</emphasis> is a Polling Consumer and therefore
|
||||
you must configure a poller (either a global default or a local sub-element).
|
||||
Once the file has been transferred to a local directory, a Message with <classname>java.io.File</classname> as its
|
||||
payload type will be generated and sent to the channel identified by the <code>channel</code> attribute.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>More on File Filtering and Large Files</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
Some times a file that just appeared in the monitored (remote) directory is not complete. Typically such a file
|
||||
will be written with some temporary extension (e.g., foo.txt.writing) and then renamed after the writing process completes.
|
||||
As a user in most cases you are only interested in files that are complete and would like to filter only those files.
|
||||
To handle these scenarios, use filtering support provided via the <code>filename-pattern</code>, <code>filename-regex</code>
|
||||
and <code>filter</code> attributes.
|
||||
|
||||
If you need a custom filter implementation simply include a reference in your adapter via the <code>filter</code> attribute.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-sftp:inbound-channel-adapter id="sftpInbondAdapter"
|
||||
channel="receiveChannel"
|
||||
session-factory="sftpSessionFactory"
|
||||
filter="customFilter"
|
||||
local-directory="file:/local-test-dir"
|
||||
remote-directory="/remote-test-dir">
|
||||
<int:poller fixed-rate="1000" max-messages-per-poll="10" task-executor="executor"/>
|
||||
</int-sftp:inbound-channel-adapter>
|
||||
|
||||
<bean id="customFilter" class="org.foo.CustomFilter"/>
|
||||
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="sftp-outbound">
|
||||
<title>SFTP Outbound Channel Adapter</title>
|
||||
|
||||
<para>
|
||||
The <emphasis>SFTP Outbound Channel Adapter</emphasis>is a special <classname>MessageHandler</classname> that will connect to the
|
||||
remote directory and will initiate a file transfer for every file it will receive as the payload of an incoming <classname>Message</classname>.
|
||||
It also supports several representations of the File so you are not limited to the File object.
|
||||
Similar to the FTP outbound adapter, the <emphasis>SFTP Outbound Channel Adapter</emphasis> supports the following payloads:
|
||||
1) <classname>java.io.File</classname> - the actual file object; 2) <classname>byte[]</classname> - byte array that represents
|
||||
the file contents; 3) <classname>java.lang.String</classname> - text that represents the file contents.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-sftp:outbound-channel-adapter id="sftpOutboundAdapter"
|
||||
session-factory="sftpSessionFactory"
|
||||
channel="inputChannel"
|
||||
charset="UTF-8"
|
||||
remote-directory="foo/bar"
|
||||
remote-filename-generator-expression="payload.getName() + '-foo'"/>]]></programlisting>
|
||||
|
||||
As you can see from the configuration above you can configure the <emphasis>SFTP Outbound Channel Adapter</emphasis> via
|
||||
the <code>outbound-channel-adapter</code> element.
|
||||
Please refer to the schema for more detail on these attributes.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>SpEL and the SFTP Outbound Adapter</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
As with many other components in Spring Integration, you can benefit from the Spring Expression Language (SpEL) support when configuring
|
||||
an <emphasis>SFTP Outbound Channel Adapter</emphasis>, by specifying two attributes <code>remote-directory-expression</code> and
|
||||
<code>remote-filename-generator-expression</code> (see above). The expression evaluation context will have the Message as its root object, thus allowing
|
||||
you to provide expressions which can dynamically compute the <emphasis>file name</emphasis> or the existing <emphasis>directory path</emphasis>
|
||||
based on the data in the Message (either from 'payload' or 'headers'). In the example above we are defining
|
||||
the <code>remote-filename-generator-expression</code> attribute with an expression
|
||||
value that computes the <emphasis>file name</emphasis> based on its original name while also appending a suffix: '-foo'.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="sftp-outbound-gateway">
|
||||
<title>SFTP Outbound Gateway</title>
|
||||
|
||||
<para>
|
||||
The <emphasis>SFTP Outbound Gateway</emphasis> provides a limited set of commands to interact with a remote SFTP server.
|
||||
<para>
|
||||
Commands supported are:
|
||||
<itemizedlist>
|
||||
<listitem>ls (list files)</listitem>
|
||||
<listitem>get (retrieve file(s))</listitem>
|
||||
<listitem>rm (remove file(s))</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
ls supports the following options:
|
||||
<itemizedlist>
|
||||
<listitem>-1 - just retrieve a list of filenames, default is to retrieve a
|
||||
list of <classname>FileInfo</classname> objects.</listitem>
|
||||
<listitem>-a - include all files (including those starting with '.')</listitem>
|
||||
<listitem>-f - do not sort the list</listitem>
|
||||
<listitem>-dirs - include directories (excluded by default)</listitem>
|
||||
<listitem>-links - include symbolic links (excluded by default)</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
In addition, filename filtering is provided, in the same manner as the
|
||||
<classname>inbound-channel-adapter</classname>.
|
||||
</para>
|
||||
<para>
|
||||
The message payload resulting from an <emphasis>ls</emphasis> operation is a list of file names,
|
||||
or a list of <classname>FileInfo</classname> objects. These objects provide
|
||||
information such as modified time, permissions etc.
|
||||
</para>
|
||||
<para>
|
||||
The remote directory that the <emphasis>ls</emphasis> command acted on is provided
|
||||
in the <classname>file_remoteDirectory</classname> header.
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>get</emphasis> supports the following option:
|
||||
<itemizedlist>
|
||||
<listitem>-P - preserve the timestamp of the remote file</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
The message payload resulting from a <emphasis>get</emphasis> operation is a
|
||||
<classname>File</classname> object representing the retrieved file.
|
||||
</para>
|
||||
<para>
|
||||
The remote directory is provided in the <classname>file_remoteDirectory</classname> header, and the filename is
|
||||
provided in the <classname>file_remoteFile</classname> header.
|
||||
</para>
|
||||
<para></para>
|
||||
<para>
|
||||
The <emphasis>rm</emphasis> command has no options.
|
||||
</para>
|
||||
<para>
|
||||
<note>
|
||||
Filters are not supported with the <emphasis>rm</emphasis> command.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
The message payload resulting from an <emphasis>rm</emphasis> operation is Boolean.TRUE if the
|
||||
remove was successful, Boolean.FALSE otherwise.
|
||||
The remote directory is provided in the <classname>file_remoteDirectory</classname> header, and the filename is
|
||||
provided in the <classname>file_remoteFile</classname> header.
|
||||
</para>
|
||||
<para></para>
|
||||
<para>
|
||||
In each case, the PATH that these commands act on is provided by the 'expression'
|
||||
property of the gateway.
|
||||
</para>
|
||||
</para>
|
||||
<para>
|
||||
Here is an example of a gateway configured for an ls command...
|
||||
<programlisting language="xml"><![CDATA[<int-ftp:outbound-gateway id="gateway1"
|
||||
session-factory="ftpSessionFactory"
|
||||
request-channel="inbound1"
|
||||
command="ls"
|
||||
command-options="-1"
|
||||
expression="payload"
|
||||
reply-channel="toSplitter"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The payload of the message sent to the toSplitter channel is a list of String objects
|
||||
containing the filename of each file. If the <classname>command-options</classname> was
|
||||
omitted, it would be a list of <classname>FileInfo</classname> objects. Options are
|
||||
provided space-delimited, e.g. <classname>command-options="-1 -dirs -links"</classname>.
|
||||
</para>
|
||||
|
||||
</section>
|
||||
|
||||
<section id="sftp-jsch-logging">
|
||||
<title>SFTP/JSCH Logging</title>
|
||||
<para>
|
||||
Since we use JSch libraries (http://www.jcraft.com/jsch/) to provide SFTP support, at times you may require
|
||||
more information from the JSch API itself, especially if something is not working properly
|
||||
(e.g., Authentication exceptions). Unfortunately JSch does not use commons-logging but instead
|
||||
relies on custom implementations of their <classname>com.jcraft.jsch.Logger</classname> interface.
|
||||
As of Spring Integration 2.0.1, we have implemented this interface. So, now all you need to do to enable
|
||||
JSch logging is to configure your logger the way you usually do. For example, here is valid configuration of a
|
||||
logger using Log4J.
|
||||
|
||||
<programlisting language="java"><![CDATA[log4j.category.com.jcraft.jsch=DEBUG]]></programlisting>
|
||||
|
||||
</para>
|
||||
</section>
|
||||
<section id="sftp-session-caching">
|
||||
<title>SFTP Session Caching</title>
|
||||
<para>
|
||||
As of version 2.1 we've exposed more flexibility with regard to session management for remote file adapters (e.g., FTP, SFTP etc).
|
||||
In previous versions the sessions were cached automatically by default. We did expose a <code>cache-sessions</code> attribute for
|
||||
disabling the auto caching, but that solution did not provide a way to configure other session caching attributes. For example, one
|
||||
of the requested features was to support a limit on the number of sessions created since a remote server may impose a limit on the
|
||||
number of client connections. To support that requirement and other configuration options, we decided to promote explicit definition
|
||||
of the <classname>CachingSessionFactory</classname> instance. That provides the <code>sessionCacheSize</code> and <code>sessionWaitTimeout</code>
|
||||
properties. As its name suggests, the <code>sessionCacheSize</code> property controls how many active sessions this adapter will
|
||||
maintain in its cache (the DEFAULT is unbounded). If the <code>sessionCacheSize</code> threshold has been reached, any attempt to
|
||||
acquire another session will block until either one of the cached sessions becomes available or until the wait time for a Session
|
||||
expires (the DEFAULT wait time is Integer.MAX_VALUE). The <code>sessionWaitTimeout</code> property enables configuration of that value.
|
||||
</para>
|
||||
<para>
|
||||
If you want your Sessions to be cached, simply configure your default Session Factory as described above and then
|
||||
wrap it in an instance of <classname>CachingSessionFactory</classname> where you may provide those additional properties.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<bean id="sftpSessionFactory" class="org.springframework.integration.sftp.session.DefaultSftpSessionFactory">
|
||||
<property name="host" value="localhost"/>
|
||||
</bean>
|
||||
|
||||
<bean id="cachingSessionFactory" class="org.springframework.integration.file.remote.session.CachingSessionFactory">
|
||||
<constructor-arg ref="sftpSessionFactory"/>
|
||||
<property name="sessionCacheSize" value="10"/>
|
||||
<property name="sessionWaitTimeout" value="1000"/>
|
||||
</bean>]]></programlisting>
|
||||
|
||||
In the above example you see a <classname>CachingSessionFactory</classname> created with the
|
||||
<code>sessionCacheSize</code> set to 10 and the <code>sessionWaitTimeout</code> set to 1 second (its value is in millliseconds).
|
||||
|
||||
</para>
|
||||
</section>
|
||||
</chapter>
|
||||
166
src/reference/docbook/splitter.xml
Normal file
@@ -0,0 +1,166 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="splitter"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Splitter</title>
|
||||
|
||||
<section id="splitter-annotation">
|
||||
<title>Introduction</title>
|
||||
|
||||
<para>The Splitter is a component whose role is to partition a message in
|
||||
several parts, and send the resulting messages to be processed
|
||||
independently. Very often, they are upstream producers in a pipeline that
|
||||
includes an Aggregator.</para>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Programming model</title>
|
||||
|
||||
<para>The API for performing splitting consists of one base class,
|
||||
<classname>AbstractMessageSplitter</classname>, which is a
|
||||
<interfacename>MessageHandler</interfacename> implementation,
|
||||
encapsulating features which are common to splitters, such as filling in
|
||||
the appropriate message headers CORRELATION_ID, SEQUENCE_SIZE, and
|
||||
SEQUENCE_NUMBER on the messages that are produced. This enables tracking
|
||||
down the messages and the results of their processing (in a typical
|
||||
scenario, these headers would be copied over to the messages that are
|
||||
produced by the various transforming endpoints), and use them, for
|
||||
example, in a
|
||||
<ulink url="http://www.eaipatterns.com/DistributionAggregate.html">
|
||||
Composed Message Processor</ulink> scenario.</para>
|
||||
|
||||
<para>An excerpt from <classname>AbstractMessageSplitter</classname> can be seen below:</para>
|
||||
|
||||
<programlisting lang="java">public abstract class AbstractMessageSplitter
|
||||
extends AbstractReplyProducingMessageConsumer {
|
||||
...
|
||||
protected abstract Object splitMessage(Message<?> message);
|
||||
|
||||
}</programlisting>
|
||||
|
||||
<para>To implement a specific Splitter in an application,
|
||||
extend <classname>AbstractMessageSplitter</classname> and implement the <code>splitMessage</code> method,
|
||||
which contains logic for splitting the messages. The return
|
||||
value may be one of the following:</para>
|
||||
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>a <interfacename>Collection</interfacename> (or subclass thereof) or an array of
|
||||
<interfacename>Message</interfacename> objects -
|
||||
in this case the messages will be sent as such (after the
|
||||
CORRELATION_ID, SEQUENCE_SIZE and SEQUENCE_NUMBER are populated).
|
||||
Using this approach gives more control to the developer, for example
|
||||
for populating custom message headers as part of the splitting
|
||||
process.</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>a <interfacename>Collection</interfacename> (or subclass thereof) or an array of
|
||||
non-Message objects - works like the prior case, except that each collection
|
||||
element will be used as a Message payload. Using this approach allows
|
||||
developers to focus on the domain objects without having to consider
|
||||
the Messaging system and produces code that is easier to test.</para>
|
||||
</listitem>
|
||||
|
||||
<listitem>
|
||||
<para>a <interfacename>Message</interfacename> or non-Message object
|
||||
(but not a Collection or an Array) - it works like the previous cases,
|
||||
except a single message will be sent out.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
|
||||
<para>In Spring Integration, any POJO can implement the splitting
|
||||
algorithm, provided that it defines a method that accepts a single
|
||||
argument and has a return value. In this case, the return value of the
|
||||
method will be interpreted as described above. The input argument might
|
||||
either be a <interfacename>Message</interfacename> or a simple POJO.
|
||||
In the latter case, the splitter will receive the payload of the incoming message.
|
||||
Since this decouples the code from the Spring Integration API and will typically be easier
|
||||
to test, it is the recommended approach.</para>
|
||||
</section>
|
||||
|
||||
|
||||
<section id="splitter-config">
|
||||
<title>Configuring Splitter</title>
|
||||
<section>
|
||||
<title>Configuring a Splitter using XML</title>
|
||||
|
||||
<para>A splitter can be configured through XML as follows:<programlisting language="xml"><int:channel id="inputChannel"/>
|
||||
|
||||
<int:splitter id="splitter" <co id="split1" />
|
||||
ref="splitterBean" <co id="split2" />
|
||||
method="split" <co id="split3" />
|
||||
input-channel="inputChannel" <co id="split4" />
|
||||
output-channel="outputChannel" <co id="split5" />/>
|
||||
|
||||
<int:channel id="outputChannel"/>
|
||||
|
||||
<beans:bean id="splitterBean" class="sample.PojoSplitter"/></programlisting><calloutlist>
|
||||
<callout arearefs="split1">
|
||||
<para>The id of the splitter is
|
||||
<emphasis>optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="split2">
|
||||
<para>A reference to a bean defined in the application context. The
|
||||
bean must implement the splitting logic as described in the section
|
||||
above .<emphasis>Optional</emphasis>.
|
||||
If reference to a bean is not provided, then it is assumed that the <emphasis>payload</emphasis>
|
||||
of the Message that arrived on the <code>input-channel</code> is
|
||||
an implementation of <interfacename>java.util.Collection</interfacename>
|
||||
and the default splitting logic will be applied to the Collection,
|
||||
incorporating each individual element into a Message and sending it to the <code>output-channel</code>.
|
||||
</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="split3">
|
||||
<para>The method (defined on the bean specified above) that
|
||||
implements the splitting logic.
|
||||
<emphasis>Optional</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="split4">
|
||||
<para>The input channel of the splitter.
|
||||
<emphasis>Required</emphasis>.</para>
|
||||
</callout>
|
||||
|
||||
<callout arearefs="split5">
|
||||
<para>The channel to which the splitter will send the results of
|
||||
splitting the incoming message. <emphasis>Optional (because incoming
|
||||
messages can specify a reply channel themselves)</emphasis>.</para>
|
||||
</callout>
|
||||
</calloutlist></para>
|
||||
<para>
|
||||
Using a <code>ref</code> attribute is generally recommended if the custom splitter implementation may be referenced in other
|
||||
<code><splitter></code> definitions. However if the custom splitter handler implementation should be scoped to a
|
||||
single definition of the <code><splitter></code>, configure an inner bean definition:
|
||||
<programlisting language="xml"><![CDATA[<int:splitter id="testSplitter" input-channel="inChannel" method="split"
|
||||
output-channel="outChannel">
|
||||
<beans:bean class="org.foo.TestSplitter"/>
|
||||
</int:spliter>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
Using both a <code>ref</code> attribute and an inner handler definition in the same <code><int:splitter></code>
|
||||
configuration is not allowed, as it creates an ambiguous condition and will result in an Exception being thrown.
|
||||
</para>
|
||||
</note>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<title>Configuring a Splitter with Annotations</title>
|
||||
|
||||
<para>The <interfacename>@Splitter</interfacename> annotation is
|
||||
applicable to methods that expect either the
|
||||
<interfacename>Message</interfacename> type or the message payload type,
|
||||
and the return values of the method should be a <interfacename>Collection</interfacename> of any type.
|
||||
If the returned values are not actual <interfacename>Message</interfacename>
|
||||
objects, then each item will be wrapped in a Message as its payload. Each
|
||||
message will be sent to the designated output channel for the endpoint
|
||||
on which the <interfacename>@Splitter</interfacename> is defined.
|
||||
<programlisting language="java">@Splitter
|
||||
List<LineItem> extractItems(Order order) {
|
||||
return order.getItems()
|
||||
}</programlisting></para>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
91
src/reference/docbook/stream.xml
Normal file
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="stream"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Stream Support</title>
|
||||
|
||||
<section id="stream-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
In many cases application data is obtained from a stream. It is <emphasis>not</emphasis> recommended to send a reference to a Stream as a message payload to a consumer. Instead messages are created from data that is read from an input stream and message payloads are written to an output stream one by one.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="stream-reading">
|
||||
<title>Reading from streams</title>
|
||||
<para>
|
||||
Spring Integration provides two adapters for streams. Both <classname>ByteStreamReadingMessageSource</classname> and
|
||||
<classname>CharacterStreamReadingMessageSource</classname> implement <interfacename>MessageSource</interfacename>.
|
||||
By configuring one of these within a channel-adapter element, the polling period can be configured,
|
||||
and the Message Bus can automatically detect and schedule them. The byte stream version requires an
|
||||
<classname>InputStream</classname>, and the character stream version requires a <classname>Reader</classname> as
|
||||
the single constructor argument. The <classname>ByteStreamReadingMessageSource</classname> also accepts the 'bytesPerMessage'
|
||||
property to determine how many bytes it will attempt to read into each <interfacename>Message</interfacename>. The
|
||||
default value is 1024
|
||||
<programlisting language="xml"><![CDATA[<bean class="org.springframework.integration.stream.ByteStreamReadingMessageSource">
|
||||
<constructor-arg ref="someInputStream"/>
|
||||
<property name="bytesPerMessage" value="2048"/>
|
||||
</bean>
|
||||
|
||||
<bean class="org.springframework.integration.stream.CharacterStreamReadingMessageSource">
|
||||
<constructor-arg ref="someReader"/>
|
||||
</bean>]]>
|
||||
</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="stream-writing">
|
||||
<title>Writing to streams</title>
|
||||
<para>
|
||||
For target streams, there are also two implementations: <classname>ByteStreamWritingMessageHandler</classname> and
|
||||
<classname>CharacterStreamWritingMessageHandler</classname>. Each requires a single constructor argument -
|
||||
<classname>OutputStream</classname> for byte streams or <classname>Writer</classname> for character streams,
|
||||
and each provides a second constructor that adds the optional 'bufferSize'. Since both of these
|
||||
ultimately implement the <interfacename>MessageHandler</interfacename> interface, they can be referenced from a
|
||||
<emphasis>channel-adapter</emphasis> configuration as described in more detail in
|
||||
<xref linkend="channel-adapter"/>.
|
||||
<programlisting language="xml"><![CDATA[<bean class="org.springframework.integration.stream.ByteStreamWritingMessageHandler">
|
||||
<constructor-arg ref="someOutputStream"/>
|
||||
<constructor-arg value="1024"/>
|
||||
</bean>
|
||||
|
||||
<bean class="org.springframework.integration.stream.CharacterStreamWritingMessageHandler">
|
||||
<constructor-arg ref="someWriter"/>
|
||||
</bean>]]>
|
||||
</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
|
||||
|
||||
<section id="stream-namespace">
|
||||
<title>Stream namespace support</title>
|
||||
<para>
|
||||
To reduce the configuration needed for stream related channel adapters there is a namespace defined. The following schema locations are needed to use it.
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/integration/stream
|
||||
http://www.springframework.org/schema/integration/stream/spring-integration-stream.xsd">]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To configure the inbound channel adapter the following code snippet shows the different configuration options that are supported.
|
||||
<programlisting language="xml"><![CDATA[<int-stream:stdin-channel-adapter id="adapterWithDefaultCharset"/>
|
||||
|
||||
<int-stream:stdin-channel-adapter id="adapterWithProvidedCharset" charset="UTF-8"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To configure the outbound channel adapter you can use the namespace support as well. The following code snippet shows the different configuration for an outbound channel adapters.
|
||||
<programlisting language="xml"><![CDATA[<int-stream:stdout-channel-adapter id="stdoutAdapterWithDefaultCharset" channel="testChannel"/>
|
||||
|
||||
<int-stream:stdout-channel-adapter id="stdoutAdapterWithProvidedCharset" charset="UTF-8" channel="testChannel"/>
|
||||
|
||||
<int-stream:stderr-channel-adapter id="stderrAdapter" channel="testChannel"/>
|
||||
|
||||
<int-stream:stdout-channel-adapter id="newlineAdapter" append-newline="true" channel="testChannel"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
</chapter>
|
||||
12
src/reference/docbook/system-management.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="system-management-chapter"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>System Management</title>
|
||||
|
||||
<xi:include href="./jmx.xml"/>
|
||||
<xi:include href="./message-history.xml"/>
|
||||
<xi:include href="./message-store.xml"/>
|
||||
<xi:include href="./control-bus.xml"/>
|
||||
|
||||
</chapter>
|
||||
176
src/reference/docbook/transactions.xml
Normal file
@@ -0,0 +1,176 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="transactions"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Transaction Support</title>
|
||||
|
||||
<section id="transaction-support">
|
||||
<title>Understanding Transactions in Message flows</title>
|
||||
<para>
|
||||
Spring Integration exposes several hooks to address transactional needs of you message flows.
|
||||
But to better understand these hooks and how you can benefit from them we must first revisit the 6 mechanisms
|
||||
that could be used to initiate Message flows and see how transactional needs of these flows
|
||||
could be addressed within each of these mechanisms.
|
||||
</para>
|
||||
<para>
|
||||
Here are the 6 mechanisms to initiate a Message flow and their short summary (details for each are provided throughout this manual):
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>Gateway Proxy</emphasis> - Your basic Messaging Gateway</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>MessageChannel</emphasis> - Direct interactions with MessageChannel methods (e.g., channel.send(message))</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Message Publisher</emphasis> - the way to initiate message flow as the by-product of method invocations on Spring beans</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Inbound Channel Adapters/Gateways</emphasis> - the way to initiate message flow based on connecting third-party
|
||||
system with Spring Integration messaging system(e.g., [JmsMessage] -> Jms Inbound Adapter[SI Message] -> SI Channel)</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Scheduler</emphasis> - the way to initiate message flow based on scheduling events distributed
|
||||
by a pre-configured Scheduler</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Poller</emphasis> - similar to the Scheduler and is the way to initiate message flow based on scheduling
|
||||
or interval-based events distributed by a pre-configured Poller</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
These 6 could be split in 2 general categories:
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para><emphasis>Message flows initiated by a USER process</emphasis> - Example scenarios in this category
|
||||
would be invoking a Gateway method or explicitly sending a Message to a MessageChannel. In other words, these message flows depend on a third
|
||||
party process (e.g., some code that we wrote) to be initiated.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para><emphasis>Message flows initiated by a DAEMON process</emphasis> - Example scenarios in this category would be a Poller
|
||||
polling a Message queue to initiate a new Message flow with the polled Message or a Scheduler scheduling the
|
||||
process by creating a new Message and initiating a message flow at a predefined time.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
<para>
|
||||
Clearly the <emphasis>Gateway Proxy</emphasis>, <emphasis>MessageChannel.send(..)</emphasis> and <emphasis>MessagePublisher</emphasis>
|
||||
all belong to the 1st category and <emphasis>Inbound Adapters/Gateways</emphasis>, <emphasis>Scheduler</emphasis> and <emphasis>Poller</emphasis>
|
||||
belong to the 2nd.
|
||||
</para>
|
||||
<para>
|
||||
So, how do we address transactional needs in various scenarios within each category and is there a need for Spring Integration
|
||||
to provide something explicitly with regard to transactions for a particular scenario? Or, can Spring's Transaction Support be leveraged instead?.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
The first and most obvious goal is NOT to re-invent something that has already been invented unless you can provide a better solution.
|
||||
In our case Spring itself provides first class support for transaction management. So our goal here is not to provide something new but rather
|
||||
delegate/use Spring to benefit from the existing support for transactions. In other words as a framework we must expose hooks to the Transaction management functionality
|
||||
provided by Spring. But since Spring Integration configuration is based on Spring Configuration it is not always necessary to expose these hooks as they
|
||||
are already exposed via Spring natively. Remember every Spring Integration component is a Spring Bean after all.
|
||||
</para>
|
||||
<para>
|
||||
With this goal in mind let's look at the two scenarios.
|
||||
</para>
|
||||
<para>
|
||||
If you think about it, Message flows that are initiated by the <emphasis>USER process</emphasis> (Category 1) and obviously configured in a Spring Application Context,
|
||||
are subject to transactional configuration of such processes and therefore don't need to be explicitly configured by Spring Integration to support transactions.
|
||||
The transaction could and should be initiated through standard Transaction support provided by Spring. The Spring Integration message flow will honor
|
||||
the transactional semantics of the components naturally because it is Spring configured. For example, a Gateway or ServiceActivator method could
|
||||
be annotated with <classname>@Transactional</classname> or <classname>TransactionInterceptor</classname> could be defined in an XML configuration
|
||||
with a point-cut expression pointing to specific methods that should be transactional.
|
||||
The bottom line is that you have full control over transaction configuration and boundaries in these scenarios.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
However, things are a bit different when it comes to Message flows initiated by the <emphasis>DAEMON process</emphasis> (Category 2).
|
||||
Although configured by the developer these flows do not directly involve a human or some other process to be initiated. These are trigger-based flows
|
||||
that are initiated by a trigger process (DAEMON process) based on the configuration of such process. For example, we could have a Scheduler
|
||||
initiating a message flow every Friday night of every week. We can also configure a trigger that initiates a Message flow every second, etc.
|
||||
So, we obviously need a way to let these trigger-based processes know of our intention to make the resulting Message flows transactional so that
|
||||
a Transaction context could be created whenever a new Message flow is initiated. In other words we need to expose some Transaction configuration, but ONLY enough
|
||||
to delegate to Transaction support already provided by Spring (as we do in other scenarios).
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration provides transactional support for Pollers. Pollers are a special type of component because
|
||||
we can call receive() within that poller task against a resource that is itself transactional thus including <emphasis>receive()</emphasis>
|
||||
call in the the boundaries of the Transaction allowing it to be rolled back in case of a task failure. If we were to add the same support
|
||||
for channels, the added transactions would affect all downstream components starting with that <emphasis>send()</emphasis> call. That is
|
||||
providing a rather wide scope for transaction demarcation without any strong reason especially when Spring already provides several ways to
|
||||
address the transactional needs of any component downstream. However the <emphasis>receive()</emphasis> method being included in a transaction
|
||||
boundary is the "strong reason" for pollers.
|
||||
</para>
|
||||
|
||||
<section id="transaction-poller">
|
||||
<title>Poller Transaction Support</title>
|
||||
<para>
|
||||
Any time you configure a Poller you can provide transactional configuration via the <emphasis>transactional</emphasis> sub-element and its attributes:
|
||||
<programlisting language="xml"><![CDATA[<int:poller max-messages-per-poll="1" fixed-rate="1000">
|
||||
<transactional transaction-manager="txManager"
|
||||
isolation="DEFAULT"
|
||||
propagation="REQUIRED"
|
||||
read-only="true"
|
||||
timeout="1000"/>
|
||||
</poller>]]></programlisting>
|
||||
As you can see this configuration looks very similar to native Spring transaction configuration. You must still provide a reference to a Transaction manager and specify
|
||||
transaction attributes or rely on defaults (e.g., if the 'transaction-manager' attribute is not specified, it will default to the bean with the name 'transactionManager').
|
||||
Internally the process would be wrapped in Spring's native Transaction where <classname>TransactionInterceptor</classname> is responsible for handling transactions.
|
||||
For more information on how to configure a Transaction Manager, the types of Transaction Managers (e.g., JTA, Datasource etc.) and other details related to
|
||||
transaction configuration please refer to Spring's Reference manual (Chapter 10 - Transaction Management).
|
||||
</para>
|
||||
<para>
|
||||
With the above configuration all Message flows initiated by this poller will be transactional. For more information and details on a
|
||||
Poller's transactional configuration please refer to section - <emphasis>21.1.1. Polling and Transactions</emphasis>.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Along with transactions, several more cross cutting concerns might need to be addressed when running a Poller. To help with that,
|
||||
the Poller element accepts an <emphasis><advice-chain> </emphasis> sub-element which allows you to define a custom chain of Advice
|
||||
instances to be applied on the Poller. (see section 4.4 for more details)
|
||||
In Spring Integration 2.0, the Poller went through the a refactoring effort and is now using a proxy mechanism to address transactional
|
||||
concerns as well as other cross cutting concerns. One of the significant changes evolving from this effort is that we
|
||||
made <emphasis><transactional></emphasis> and <emphasis><advice-chain></emphasis> elements mutually exclusive.
|
||||
The rationale behind this is that if you need more than one advice, and one of them is Transaction advice, then you can simply
|
||||
include it in the <emphasis><advice-chain></emphasis> with the same convenience as before but with much more control
|
||||
since you now have an option to position any advice in the desired order.
|
||||
<programlisting language="xml"><![CDATA[<int:poller max-messages-per-poll="1" fixed-rate="10000">
|
||||
<advice-chain>
|
||||
<ref bean="txAdvice"/>
|
||||
<ref bean="someAotherAdviceBean" />
|
||||
<beans:bean class="foo.bar.SampleAdvice"/>
|
||||
</advice-chain>
|
||||
</poller>
|
||||
|
||||
<tx:advice id="txAdvice" transaction-manager="txManager">
|
||||
<tx:attributes>
|
||||
<tx:method name="get*" read-only="true"/>
|
||||
<tx:method name="*"/>
|
||||
</tx:attributes>
|
||||
</tx:advice>
|
||||
]]></programlisting>
|
||||
|
||||
As yo can see from the example above, we have provided a very basic XML-based configuration of Spring Transaction advice - "txAdvice" and
|
||||
included it within the <emphasis><advice-chain></emphasis> defined by the Poller.
|
||||
If you only need to address transactional concerns of the Poller, then you can still use the <emphasis><transactional></emphasis> element
|
||||
as a convinience.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="transaction-boundaries">
|
||||
<title>Transaction Boundaries</title>
|
||||
<para>
|
||||
Another important factor is the boundaries of Transactions within a Message flow.
|
||||
When a transaction is started, the transaction context is bound to the current thread. So regardless of how many endpoints and channels you have in your
|
||||
Message flow your transaction context will be preserved as long as you are ensuring that the flow continues on the same thread.
|
||||
As soon as you break it by introducing a <emphasis>Pollable Channel</emphasis> or <emphasis>Executor Channel</emphasis> or initiate a new thread manually
|
||||
in some service, the Transactional boundary will be broken as well. Essentially the Transaction will END right there, and if
|
||||
a successful handoff has transpired between the threads, the flow would be considered a success and a COMMIT signal would be sent
|
||||
even though the flow will continue and might still result in an Exception somewhere downstream. If such a flow were synchronous, that Exception could
|
||||
be thrown back to the initiator of the Message flow who is also the initiator of the transactional context and the transaction would result in a ROLLBACK.
|
||||
The middle ground is to use transactional channels at any point where a thread boundary is being broken. For example, you can use a Queue-backed Channel
|
||||
that delegates to a transactional MessageStore strategy, or you could use a JMS-backed channel.
|
||||
</para>
|
||||
</section>
|
||||
</chapter>
|
||||
272
src/reference/docbook/transformer.xml
Normal file
@@ -0,0 +1,272 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="transformer"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Transformer</title>
|
||||
|
||||
<section id="transformer-introduction">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
Message Transformers play a very important role in enabling the loose-coupling of Message Producers and Message
|
||||
Consumers. Rather than requiring every Message-producing component to know what type is expected by the next
|
||||
consumer, Transformers can be added between those components. Generic transformers, such as one that converts a
|
||||
String to an XML Document, are also highly reusable.
|
||||
</para>
|
||||
<para>
|
||||
For some systems, it may be best to provide a
|
||||
<ulink url="http://www.eaipatterns.com/CanonicalDataModel.html">Canonical Data Model</ulink>, but Spring
|
||||
Integration's general philosophy is not to require any particular format. Rather, for maximum flexibility, Spring
|
||||
Integration aims to provide the simplest possible model for extension. As with the other endpoint types, the use
|
||||
of declarative configuration in XML and/or Annotations enables simple POJOs to be adapted for the role of Message
|
||||
Transformers. These configuration options will be described below.
|
||||
<note>
|
||||
For the same reason of maximizing flexibility, Spring does not require XML-based Message payloads.
|
||||
Nevertheless, the framework does provide some convenient Transformers for dealing with XML-based payloads if
|
||||
that is indeed the right choice for your application. For more information on those transformers, see
|
||||
<xref linkend="xml"/>.
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="transformer-config">
|
||||
<title>Configuring Transformer</title>
|
||||
|
||||
|
||||
<section id="transformer-namespace">
|
||||
<title>Configuring Transformer with XML</title>
|
||||
<para>
|
||||
The <transformer> element is used to create a Message-transforming endpoint. In addition to "input-channel"
|
||||
and "output-channel" attributes, it requires a "ref". The "ref" may either point to an Object that contains the
|
||||
@Transformer annotation on a single method (see below) or it may be combined with an explicit method name value
|
||||
provided via the "method" attribute.
|
||||
<programlisting language="xml"><![CDATA[<int:transformer id="testTransformer" ref="testTransformerBean" input-channel="inChannel"
|
||||
method="transform" output-channel="outChannel"/>
|
||||
<beans:bean id="testTransformerBean" class="org.foo.TestTransformer" />]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Using a "ref" attribute is generally recommended if the custom transformer handler implementation can be reused in
|
||||
other <code><transformer></code> definitions. However if the custom transformer handler implementation should
|
||||
be scoped to a single definition of the <code><transformer></code>, you can define an inner bean definition:
|
||||
<programlisting language="xml"><![CDATA[<int:transformer id="testTransformer" input-channel="inChannel" method="transform"
|
||||
output-channel="outChannel">
|
||||
<beans:bean class="org.foo.TestTransformer"/>
|
||||
</transformer>]]></programlisting>
|
||||
</para>
|
||||
<note>
|
||||
<para>
|
||||
Using both the "ref" attribute and an inner handler definition in the same <code><transformer></code>
|
||||
configuration is not allowed, as it creates an ambiguous condition and will result in an Exception being thrown.
|
||||
</para>
|
||||
</note>
|
||||
<para>
|
||||
The method that is used for transformation may expect either the <interfacename>Message</interfacename> type or
|
||||
the payload type of inbound Messages. It may also accept Message header values either individually or as a full
|
||||
map by using the <code>@Header</code> and <code>@Headers</code> parameter annotations respectively. The return value of the method can be
|
||||
any type. If the return value is itself a <interfacename>Message</interfacename>, that will be passed along to
|
||||
the transformer's output channel.
|
||||
</para>
|
||||
<para>
|
||||
As of Spring Integration 2.0, a Message Transformer's transformation method can no longer return <code>null</code>.
|
||||
Returning <code>null</code> will result in an exception since a Message Transformer should always be expected to
|
||||
transform each source Message into a valid target Message. In other words, a Message Transformer should not be used
|
||||
as a Message Filter since there is a dedicated <filter> option for that. However, if you do need this type of
|
||||
behavior (where a component might return NULL and that should not be considered an error), a
|
||||
<emphasis>service-activator</emphasis> could be used. Its <code>requires-reply</code> value is FALSE by default,
|
||||
but that can be set to TRUE in order to have Exceptions thrown for NULL return values as with the transformer.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Transformers and Spring Expression Language (SpEL)</emphasis>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Just like Routers, Aggregators and other components, as of Spring Integration 2.0 Transformers can also benefit from SpEL support
|
||||
(http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/expressions.html)
|
||||
whenever transformation logic is relatively simple.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:transformer input-channel="inChannel"
|
||||
output-channel="outChannel"
|
||||
expression="payload.toUpperCase() + '- [' + T(java.lang.System).currentTimeMillis() + ']'"/>]]></programlisting>
|
||||
|
||||
In the above configuration we are achieving a simple transformation of the <emphasis>payload</emphasis> with a simple SpEL
|
||||
expression and without writing a custom transformer. Our <emphasis>payload</emphasis> (assuming String) will be
|
||||
upper-cased and concatenated with the current timestamp with some simple formatting.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<emphasis>Common Transformers</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
There are also a few Transformer implementations available out of the box. Because, it is fairly common
|
||||
to use the <methodname>toString()</methodname> representation of an Object, Spring Integration provides an
|
||||
<classname>ObjectToStringTransformer</classname> whose output is a Message with a String payload. That String
|
||||
is the result of invoking the toString() operation on the inbound Message's payload.
|
||||
|
||||
<programlisting language="xml"><![CDATA[ <int:object-to-string-transformer input-channel="in" output-channel="out"/>]]></programlisting>
|
||||
|
||||
A potential example for this would be sending some arbitrary object to the 'outbound-channel-adapter' in the
|
||||
<emphasis>file</emphasis> namespace. Whereas that Channel Adapter only supports String, byte-array, or
|
||||
<classname>java.io.File</classname> payloads by default, adding this transformer immediately before the
|
||||
adapter will handle the necessary conversion. Of course, that works fine as long as the result of the
|
||||
<methodname>toString()</methodname> call is what you want to be written to the File. Otherwise, you can
|
||||
just provide a custom POJO-based Transformer via the generic 'transformer' element shown previously.
|
||||
<tip>
|
||||
When debugging, this transformer is not typically necessary since the 'logging-channel-adapter' is capable
|
||||
of logging the Message payload. Refer to <xref linkend="channel-wiretap"/> for more detail.
|
||||
</tip>
|
||||
</para>
|
||||
<para>
|
||||
If you need to serialize an Object to a byte array or deserialize a byte array back into an Object,
|
||||
Spring Integration provides symmetrical serialization transformers. These will use standard Java serialization
|
||||
by default, but you can provide an implementation of Spring 3.0's Serializer or Deserializer strategies via the
|
||||
'serializer' and 'deserializer' attributes, respectively.
|
||||
|
||||
<programlisting language="xml"><![CDATA[ <int:payload-serializing-transformer input-channel="objectsIn" output-channel="bytesOut"/>
|
||||
|
||||
<int:payload-deserializing-transformer input-channel="bytesIn" output-channel="objectsOut"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Object-to-Map Transformer</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
Spring Integration also provides <emphasis>Object-to-Map</emphasis> and <emphasis>Map-to-Object</emphasis> transformers which
|
||||
utilize the Spring Expression Language (SpEL) to serialize and de-serialize the object graphs. The object hierarchy is introspected
|
||||
to the most primitive types (String, int, etc.). The path to this type is described via SpEL, which becomes the <emphasis>key</emphasis> in the
|
||||
transformed Map. The primitive type becomes the value.
|
||||
</para>
|
||||
<para>
|
||||
For example:
|
||||
<programlisting language="java"><![CDATA[public class Parent{
|
||||
private Child child;
|
||||
private String name;
|
||||
// setters and getters are omitted
|
||||
}
|
||||
|
||||
public class Child{
|
||||
private String name;
|
||||
private List<String> nickNames;
|
||||
// setters and getters are omitted
|
||||
}]]></programlisting>
|
||||
... will be transformed to a Map which looks like this:
|
||||
<code>{person.name=George, person.child.name=Jenna, person.child.nickNames[0]=Bimbo . . . etc}</code>
|
||||
</para>
|
||||
<para>
|
||||
The SpEL-based Map allows you to describe the object structure without sharing the actual types allowing
|
||||
you to restore/rebuild the object graph into a differently typed Object graph as long as you maintain the structure.
|
||||
</para>
|
||||
<para>
|
||||
For example:
|
||||
The above structure could be easily restored back to the following Object graph via the Map-to-Object transformer:
|
||||
<programlisting language="java"><![CDATA[public class Father {
|
||||
private Kid child;
|
||||
private String name;
|
||||
// setters and getters are omitted
|
||||
}
|
||||
|
||||
public class Kid {
|
||||
private String name;
|
||||
private List<String> nickNames;
|
||||
// setters and getters are omitted
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
To configure these transformers, Spring Integration provides namespace support
|
||||
Object-to-Map:
|
||||
<programlisting language="xml"><![CDATA[<int:object-to-map-transformer input-channel="directInput" output-channel="output"/>]]></programlisting>
|
||||
Map-to-Object
|
||||
<programlisting language="xml"><![CDATA[<int:map-to-object-transformer input-channel="input"
|
||||
output-channel="output"
|
||||
type="org.foo.Person"/>]]></programlisting>
|
||||
or
|
||||
<programlisting language="xml"><![CDATA[<int:map-to-object-transformer input-channel="inputA"
|
||||
output-channel="outputA"
|
||||
ref="person"/>
|
||||
<bean id="person" class="org.foo.Person" scope="prototype"/>
|
||||
]]></programlisting>
|
||||
|
||||
</para>
|
||||
<note>
|
||||
NOTE: 'ref' and 'type' attributes are mutually exclusive. You can only use one.
|
||||
Also, if using the 'ref' attribute, you must point to a 'prototype' scoped bean, otherwise
|
||||
a BeanCreationException will be thrown.
|
||||
</note>
|
||||
<para>
|
||||
<emphasis>JSON Transformers</emphasis>
|
||||
</para>
|
||||
<para>
|
||||
<emphasis>Object to JSON</emphasis> and <emphasis>JSON to Object</emphasis> transformers are provided.
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="xml"><![CDATA[<int:object-to-json-transformer input-channel="objectMapperInput"/>]]></programlisting>
|
||||
<programlisting language="xml"><![CDATA[<int:json-to-object-transformer input-channel="objectMapperInput"
|
||||
type="foo.MyDomainObject"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
These use a vanilla Jackson ObjectMapper by default. If you wish to customize the ObjectMapper (for example,
|
||||
to configure the 'ALLOW_COMMENTS' feature when parsing JSON), you can supply a reference to your custom ObjectMapper bean using
|
||||
the object-mapper attribute.
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="xml"><![CDATA[<int:json-to-object-transformer input-channel="objectMapperInput"
|
||||
type="foo.MyDomainObject" object-mapper="customObjectMapper"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
You may wish to consider using a FactoryBean or simple factory method to create the ObjectMapper with
|
||||
the required characteristics.
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="java"><![CDATA[public class ObjectMapperFactory {
|
||||
|
||||
public static ObjectMapper getMapper() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
|
||||
return mapper;
|
||||
}
|
||||
}]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
<programlisting language="xml"><![CDATA[<bean id="customObjectMapper" class="foo.ObjectMapperFactory"
|
||||
factory-method="getMapper"/>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="transformer-annotation">
|
||||
<title>Configuring a Transformer with Annotations</title>
|
||||
<para>
|
||||
The <interfacename>@Transformer</interfacename> annotation can also be added to methods that expect either the
|
||||
<interfacename>Message</interfacename> type or the message payload type. The return value will be handled in the
|
||||
exact same way as described above in the section describing the <transformer> element.
|
||||
<programlisting language="java">@Transformer
|
||||
Order generateOrder(String productId) {
|
||||
return new Order(productId);
|
||||
}</programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Transformer methods may also accept the @Header and @Headers annotations that is documented in <xref linkend="annotations"/>
|
||||
<programlisting language="java">@Transformer
|
||||
Order generateOrder(String productId, @Header("customerName") String customer) {
|
||||
return new Order(productId, customer);
|
||||
}</programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
|
||||
|
||||
<section id="header-filter">
|
||||
<title>Header Filter</title>
|
||||
|
||||
Some times your transformation use case might be as simple as removing a few headers.
|
||||
For such a use case, Spring Integration provides a <emphasis>Header Filter</emphasis> which allows you to specify certain header names
|
||||
that should be removed from the output Message (e.g. for security reasons or a value that was only needed temporarily).
|
||||
Basically the <emphasis>Header Filter</emphasis> is the opposite of the <emphasis>Header Enricher</emphasis>.
|
||||
The latter is discussed in <xref linkend="header-enricher"/>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int:header-filter input-channel="inputChannel"
|
||||
output-channel="outputChannel" header-names="lastName, state"/>]]></programlisting>
|
||||
|
||||
As you can see, configuration of a <emphasis>Header Filter</emphasis> is quite simple. It is a typical endpoint with input/output channels
|
||||
and a <code>header-names</code> attribute. That attribute accepts the names of the header(s) (delimited by commas if there are multiple)
|
||||
that need to be removed. So, in the above example the headers named 'lastName' and 'state' will not be present on the outbound Message.
|
||||
</section>
|
||||
|
||||
</section>
|
||||
292
src/reference/docbook/twitter.xml
Normal file
@@ -0,0 +1,292 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="twitter"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
|
||||
<title>Twitter Adapter</title>
|
||||
<para>
|
||||
Spring Integration provides support for interacting with Twitter. With the Twitter adapters you can both
|
||||
receive and send Twitter messages. You can also perform a Twitter search based on a schedule and publish
|
||||
the search results within Messages.
|
||||
</para>
|
||||
|
||||
<section id="twitter-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
Twitter is a social networking and micro-blogging service that enables its users to send and read messages known as tweets.
|
||||
Tweets are text-based posts of up to 140 characters displayed on the author's profile page and delivered to the author's
|
||||
subscribers who are known as followers.
|
||||
</para>
|
||||
<para>
|
||||
<important>
|
||||
Previous versions of Spring Integration were dependent upon the <link linkend="http://twitter4j.org/en/index.html">Twitter4J API</link>,
|
||||
but with the release of <link linkend="http://www.springsource.org/spring-social">Spring Social 1.0 GA</link>,
|
||||
Spring Integration, as of version 2.1, now builds directly upon Spring Social's Twitter support, instead of Twitter4J.
|
||||
</important>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
Spring Integration provides a convenient namespace configuration to define Twitter artifacts. You can enable it by adding
|
||||
the following within your XML header.
|
||||
<programlisting language="xml"><![CDATA[xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration/twitter
|
||||
http://www.springframework.org/schema/integration/twitter/spring-integration-twitter.xsd"]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="twitter-oauth">
|
||||
<title>Twitter OAuth Configuration</title>
|
||||
|
||||
<para>
|
||||
The Twitter API allows for both authenticated and anonymous operations. For authenticated operations Twitter uses OAuth
|
||||
- an authentication protocol that allows users to approve an application to act on their behalf without
|
||||
sharing their password. More information can be found at <link linkend="http://oauth.net/">http://oauth.net/</link> or
|
||||
in this article <link linkend="http://hueniverse.com/oauth/">http://hueniverse.com/oauth/</link> from Hueniverse.
|
||||
Please also see <link linkend="http://dev.twitter.com/pages/oauth_faq">OAuth FAQ</link> for more information about OAuth and Twitter.
|
||||
</para>
|
||||
<para>
|
||||
In order to use OAuth authentication/authorization with Twitter you must create a new Application on the Twitter Developers site.
|
||||
Follow the directions below to create a new application and obtain consumer keys and an access token:
|
||||
</para>
|
||||
<para>
|
||||
<itemizedlist>
|
||||
<listitem>
|
||||
<para>Go to <link linkend="http://dev.twitter.com/">http://dev.twitter.com/</link></para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>Click on the <code>Register an app</code> link and fill out all required fields on the form provided;
|
||||
set <code>Application Type</code> to <code>Client</code> and depending on the nature of your application select
|
||||
<code>Default Access Type</code> as <emphasis>Read & Write</emphasis> or <emphasis>Read-only</emphasis>
|
||||
and Submit the form. If everything is successful you'll be presented with the <code>Consumer Key</code>
|
||||
and <code>Consumer Secret</code>. Copy both values in a safe place.</para>
|
||||
</listitem>
|
||||
<listitem>
|
||||
<para>On the same page you should see a <code>My Access Token</code> button on the side bar (right).
|
||||
Click on it and you'll be presented with two more values: <code>Access Token</code> and <code>Access Token Secret</code>.
|
||||
Copy these values in a safe place as well.</para>
|
||||
</listitem>
|
||||
</itemizedlist>
|
||||
</para>
|
||||
|
||||
</section>
|
||||
<section>
|
||||
<title>Twitter Template</title>
|
||||
|
||||
<para>
|
||||
As mentioned above, Spring Integration relies upon Spring Social, and that library provides an implementation of the template
|
||||
pattern, <classname>org.springframework.social.twitter.api.impl.TwitterTemplate</classname> to interact with Twitter.
|
||||
For anonymous operations (e.g., search), you don't have to define an instance of <classname>TwitterTemplate</classname> explicitly,
|
||||
since a default instance will be created and injected into the endpoint. However, for authenticated operations
|
||||
(update status, send direct message, etc.), you must configure a <classname>TwitterTemplate</classname> as a bean and
|
||||
inject it explicitly into the endpoint, because the authentication configuration is required.
|
||||
Below is a sample configuration of TwitterTemplate:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<bean id="twitterTemplate" class="org.springframework.social.twitter.api.impl.TwitterTemplate">
|
||||
<constructor-arg value="4XzBPacJQxyBzzzH"/>
|
||||
<constructor-arg value="AbRxUAvyCtqQtvxFK8w5ZMtMj20KFhB6o"/>
|
||||
<constructor-arg value="21691649-4YZY5iJEOfz2A9qCFd9SjBRGb3HLmIm4HNE"/>
|
||||
<constructor-arg value="AbRxUAvyNCtqQtxFK8w5ZMtMj20KFhB6o"/>
|
||||
</bean>]]></programlisting>
|
||||
<note>The values above are not real.</note>
|
||||
|
||||
As you can see from the configuration above, all we need to do is to provide
|
||||
OAuth <code>attributes</code> as constructor arguments. The values would be those you obtained in the previous step.
|
||||
The order of constructor arguments is: 1) <code>consumerKey</code>, 2) <code>consumerSecret</code>,
|
||||
3) <code>accessToken</code>, and 4) <code>accessTokenSecret</code>.
|
||||
</para>
|
||||
|
||||
<para>
|
||||
A more practical way to manage OAuth connection attributes would be via Spring's property placeholder support by simply
|
||||
creating a property file (e.g., oauth.properties):
|
||||
|
||||
<programlisting language="java"><![CDATA[twitter.oauth.consumerKey=4XzBPacJQxyBzzzH
|
||||
twitter.oauth.consumerSecret=AbRxUAvyCtqQtvxFK8w5ZMtMj20KFhB6o
|
||||
twitter.oauth.accessToken=21691649-4YZY5iJEOfz2A9qCFd9SjBRGb3HLmIm4HNE
|
||||
twitter.oauth.accessTokenSecret=AbRxUAvyNCtqQtxFK8w5ZMtMj20KFhB6o]]></programlisting>
|
||||
|
||||
Then, you can configure a <code>property-placeholder</code> to point to the above property file:
|
||||
|
||||
<programlisting language="java"><![CDATA[<context:property-placeholder
|
||||
location="classpath:oauth.properties"/>
|
||||
|
||||
<bean id="twitterTemplate" class="org.springframework.social.twitter.api.impl.TwitterTemplate">
|
||||
<constructor-arg value="${twitter.oauth.consumerKey}"/>
|
||||
<constructor-arg value="${twitter.oauth.consumerSecret}"/>
|
||||
<constructor-arg value="${twitter.oauth.accessToken}"/>
|
||||
<constructor-arg value="${twitter.oauth.accessTokenSecret}"/>
|
||||
</bean>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="twitter-inbound">
|
||||
<title>Twitter Inbound Adapters</title>
|
||||
<para>
|
||||
Twitter inbound adapters allow you to receive Twitter Messages. There are several types of
|
||||
<link linkend="http://support.twitter.com/groups/31-twitter-basics/topics/109-tweets-messages/articles/119138-types-of-tweets-and-where-they-appear">twitter messages, or tweets</link>
|
||||
</para>
|
||||
<para>
|
||||
The current release of Spring Integration provides support for receiving tweets as <emphasis>Timeline Updates</emphasis>,
|
||||
<emphasis>Direct Messages</emphasis>, <emphasis>Mention Messages</emphasis> as well as Search Results.
|
||||
</para>
|
||||
<para>
|
||||
Every Inbound Twitter Channel Adapter is a <emphasis>Polling Consumer</emphasis> which means you have to provide a poller
|
||||
configuration. However, there is one important thing you must understand about Twitter since its inner-workings are slightly
|
||||
different than other polling consumers. Twitter defines a concept of Rate Limiting. You can read more about
|
||||
it here: <link linkend="http://dev.twitter.com/pages/rate-limiting">Rate Limiting</link>. In a nutshell, Rate Limiting
|
||||
is the way Twitter manages how often an application can poll for updates. You should consider this when setting your
|
||||
poller intervals, but we are also doing a few things to limit excessively aggressive polling within our adapters.
|
||||
</para>
|
||||
<para>
|
||||
Another issue that we need to worry about is handling duplicate Tweets. The same adapter (e.g., Search or Timeline Update)
|
||||
while polling on Twitter may receive the same values more than once. For example if you keep searching on Twitter with the same search
|
||||
criteria you'll end up with the same set of tweets unless some other new tweet that matches your search criteria was posted
|
||||
in between your searches. In that situation you'll get all the tweets you had before plus the new one. But what you really
|
||||
want is only the new tweet(s). Spring Integration provides an elegant mechanism for handling these situations.
|
||||
The latest Tweet timestamp will be stored in an instance of the <classname>org.springframework.integration.store.MetadataStore</classname> which is a
|
||||
strategy interface designed for storing various types of metadata (e.g., last retrieved tweet in this case). That strategy helps components such as
|
||||
these Twitter adapters avoid duplicates. By default, Spring Integration will look for a bean of type
|
||||
<classname>org.springframework.integration.store.MetadataStore</classname> in the ApplicationContext.
|
||||
If one is found then it will be used, otherwise it will create a new instance of <classname>SimpleMetadataStore</classname>
|
||||
which is a simple in-memory implementation that will only persist metadata within the lifecycle of the currently running application context.
|
||||
That means upon restart you may end up with duplicate entries. If you need to persist metadata between Application Context
|
||||
restarts, you may use the <classname>PropertiesPersistingMetadataStore</classname> (which is backed by a properties file, and a persister
|
||||
strategy), or you may create your own custom implementation of the <classname>MetadataStore</classname> interface (e.g., JdbcMetadatStore)
|
||||
and configure it as a bean named 'metadataStore' within the Application Context.
|
||||
<programlisting language="java"><![CDATA[<bean id="metadataStore" class="org.springframework.integration.store.PropertiesPersistingMetadataStore"/>
|
||||
]]></programlisting>
|
||||
The Poller that is configured as part of any Inbound Twitter Adapter (see below) will simply poll from this MetadataStore to determine the latest tweet
|
||||
received.
|
||||
</para>
|
||||
<section id="inbound-twitter-update">
|
||||
<title>Inbound Message Channel Adapter</title>
|
||||
<para>
|
||||
This adapter allows you to receive updates from everyone you follow. It's essentially the "Timeline Update" adapter.
|
||||
<programlisting language="xml"><![CDATA[<int-twitter:inbound-channel-adapter
|
||||
twitter-template="twitterTemplate"
|
||||
channel="inChannel">
|
||||
<int:poller fixed-rate="5000" max-messages-per-poll="3"/>
|
||||
</int-twitter:inbound-channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="inbound-twitter-direct">
|
||||
<title>Direct Inbound Message Channel Adapter</title>
|
||||
<para>
|
||||
This adapter allows you to receive Direct Messages that were sent to you from other Twitter users.
|
||||
<programlisting language="xml"><![CDATA[<int-twitter:dm-inbound-channel-adapter
|
||||
twitter-template="twiterTemplate"
|
||||
channel="inboundDmChannel">
|
||||
<int-poller fixed-rate="5000" max-messages-per-poll="3"/>
|
||||
</int-twitter:dm-inbound-channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="inbound-twitter-mention">
|
||||
<title>Mentions Inbound Message Channel Adapter</title>
|
||||
<para>
|
||||
This adapter allows you to receive Twitter Messages that Mention you via @user syntax.
|
||||
<programlisting language="xml"><![CDATA[<int-twitter:mentions-inbound-channel-adapter
|
||||
twitter-template="twiterTemplate"
|
||||
channel="inboundMentionsChannel">
|
||||
<int:poller fixed-rate="5000" max-messages-per-poll="3"/>
|
||||
</int-twitter:mentions-inbound-channel-adapter>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="inbound-twitter-search">
|
||||
<title>Search Inbound Message Channel Adapter</title>
|
||||
<para>
|
||||
This adapter allows you to perform searches. As you can see it is not necessary to define twitter-template
|
||||
since a search can be performed anonymously, however you must define a search query.
|
||||
<programlisting language="xml"><![CDATA[<int-twitter:search-inbound-channel-adapter
|
||||
query="#springintegration"
|
||||
channel="inboundMentionsChannel">
|
||||
<int:poller fixed-rate="5000" max-messages-per-poll="3"/>
|
||||
</int-twitter:search-inbound-channel-adapter>]]></programlisting>
|
||||
|
||||
</para>
|
||||
<para>
|
||||
Here is a link that will help you learn more about Twitter queries: http://search.twitter.com/operators
|
||||
</para>
|
||||
</section>
|
||||
<para>
|
||||
As you can see the configuration of all of these adapters is very similar to other inbound adapters with one exception.
|
||||
Some may need to be injected with the <code>twitter-template</code>. Once received each Twitter Message would be
|
||||
encapsulated in a Spring Integration Message and sent to the channel specified by the <code>channel</code> attribute.
|
||||
Currently the Payload type of any Message is <classname>org.springframework.integration.twitter.core.Tweet</classname>
|
||||
which is very similar to the object with the same name in Spring Social. As we migrate to Spring Social
|
||||
we'll be depending on their API and some of the artifacts that are currently in use will be obsolete, however we've already
|
||||
made sure that the impact of such migration is minimal by aligning our API with the current state (at the time of writing)
|
||||
of Spring Social.
|
||||
</para>
|
||||
<para>
|
||||
To get the text from the <classname>org.springframework.social.twitter.api.Tweet</classname>
|
||||
simply invoke the <code>getText()</code> method.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="twitter-outbound">
|
||||
<title>Twitter Outbound Adapter</title>
|
||||
<para>
|
||||
Twitter outbound channel adapters allow you to send Twitter Messages, or tweets.
|
||||
</para>
|
||||
<para>
|
||||
The current release of Spring Integration supports sending <emphasis>Status Update Messages</emphasis> and <emphasis>Direct Messages</emphasis>.
|
||||
Twitter outbound channel adapters will take the Message payload and send it as a Twitter message. Currently the only supported payload type is
|
||||
<classname>String</classname>, so consider adding a <emphasis>transformer</emphasis> if the payload of the incoming message is not a String.
|
||||
</para>
|
||||
|
||||
<section id="outbound-twitter-update">
|
||||
<title>Twitter Outbound Update Channel Adapter</title>
|
||||
<para>
|
||||
This adapter allows you to send regular status updates by simply sending a Message to the channel
|
||||
identified by the <code>channel</code> attribute.
|
||||
<programlisting language="xml"><![CDATA[<int-twitter:outbound-channel-adapter
|
||||
twitter-template="twitterTemplate"
|
||||
channel="twitterChannel"/>]]></programlisting>
|
||||
The only extra configuration that is required for this adapter is the <code>twitter-template</code> reference.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="outbound-twitter-direct">
|
||||
<title>Twitter Outbound Direct Message Channel Adapter</title>
|
||||
<para>
|
||||
This adapter allows you to send Direct Twitter Messages (i.e., @user) by simply sending a Message to the channel
|
||||
identified by the <code>channel</code> attribute.
|
||||
<programlisting language="xml"><![CDATA[<int-twitter:dm-outbound-channel-adapter
|
||||
twitter-template="twitterTemplate"
|
||||
channel="twitterChannel"/>]]></programlisting>
|
||||
The only extra configuration that is required for this adapter is the <code>twitter-template</code> reference.
|
||||
</para>
|
||||
<para>
|
||||
When it comes to Twitter Direct Messages, you must specify who you are sending the message to - the <emphasis>target userid</emphasis>.
|
||||
The Twitter Outbound Direct Message Channel Adapter will look for a target userid in the Message headers under the name
|
||||
<code>twitter_dmTargetUserId</code> which is also identified by the following constant: <classname>TwitterHeaders.DM_TARGET_USER_ID</classname>.
|
||||
So when creating a Message all you need to do is add a value for that header.
|
||||
|
||||
<programlisting language="java"><![CDATA[Message message = MessageBuilder.withPayload("hello")
|
||||
.setHeader(TwitterHeaders.DM_TARGET_USER_ID, "z_oleg").build();]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
The above approach works well if you are creating the Message programmatically. However it's more common to
|
||||
provide the header value within a messaging flow. The value can be provided by an upstream <header-enricher>.
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="in" output-channel="out">
|
||||
<int:header name="twitter_dmTargetUserId" value="z_oleg"/>
|
||||
</int:header-enricher>]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>It's quite common that the value must be determined dynamically. For those cases you can take advantage
|
||||
of SpEL support within the <header-enricher>.
|
||||
<programlisting language="xml"><![CDATA[<int:header-enricher input-channel="in" output-channel="out">
|
||||
<int:header name="twitter_dmTargetUserId" expression="@twitterIdService.lookup(headers.username)"/>
|
||||
</int:header-enricher>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<para>
|
||||
<important>Twitter does not allow you to post duplicate Messages. This is a common problem during testing when
|
||||
the same code works the first time but does not work the second time. So, make sure to change the content of the Message
|
||||
each time. Another thing that works well for testing is to append a timestamp to the end of each message.
|
||||
</important>
|
||||
</para>
|
||||
</section>
|
||||
</chapter>
|
||||
337
src/reference/docbook/whats-new.xml
Normal file
@@ -0,0 +1,337 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="whats-new"
|
||||
xmlns:xi="http://www.w3.org/2001/XInclude"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>What's new in Spring Integration 2.1?</title>
|
||||
<para>
|
||||
This chapter provides an overview of the new features and improvements
|
||||
that have been introduced with Spring Integration 2.1 If you are interested
|
||||
in even more detail, please take a look at the Issue Tracker tickets that
|
||||
were resolved as part of the 2.1 development process:
|
||||
</para>
|
||||
|
||||
<para><ulink url="https://jira.springsource.org/secure/ReleaseNote.jspa?projectId=10121&version=11668">Release Notes for Spring Integration 2.1 M1</ulink></para>
|
||||
<para><ulink url="https://jira.springsource.org/secure/ReleaseNote.jspa?projectId=10121&version=12200">Release Notes for Spring Integration 2.1 M2</ulink></para>
|
||||
<para><ulink url="https://jira.springsource.org/secure/ReleaseNote.jspa?projectId=10121&version=12640">Release Notes for Spring Integration 2.1 M3</ulink></para>
|
||||
|
||||
<section id="2.1-new-components">
|
||||
<title>New Components</title>
|
||||
<section id="2.1-new-scripting-support">
|
||||
<title>JSR-223 Scripting Support</title>
|
||||
<para>
|
||||
In Spring Integration 2.0, support for
|
||||
<ulink url="http://groovy.codehaus.org/">Groovy</ulink> was added. With
|
||||
Spring Integration 2.1 we expanded support for additional languages
|
||||
substantially by implementing support for
|
||||
<ulink url="http://www.jcp.org/en/jsr/detail?id=223">JSR-223</ulink>
|
||||
(Scripting for the Java™ Platform). Now you have the
|
||||
ability to use any scripting language that supports JSR-223 including:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>Javascript</listitem>
|
||||
<listitem>Ruby/JRuby</listitem>
|
||||
<listitem>Python/Jython</listitem>
|
||||
<listitem>Groovy</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
For further details please see <xref linkend="scripting"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-gemfire-support">
|
||||
<title>GemFire Support</title>
|
||||
<para>
|
||||
Spring Integration provides support for
|
||||
<ulink url="http://www.vmware.com/products/vfabric-gemfire/overview.html">GemFire</ulink> by providing
|
||||
inbound adapters for entry and continuous query events, an outbound
|
||||
adapter to write entries to the cache, and
|
||||
<ulink url="http://static.springsource.org/spring-integration/api/org/springframework/integration/store/MessageStore.html">
|
||||
<interfacename>MessageStore</interfacename></ulink> and
|
||||
<ulink url="http://static.springsource.org/spring-integration/api/org/springframework/integration/store/MessageGroupStore.html">
|
||||
<interfacename>MessageGroupStore</interfacename></ulink>
|
||||
implementations. Spring integration leverages
|
||||
the <ulink url="http://www.springsource.org/spring-gemfire"><emphasis>Spring Gemfire</emphasis></ulink> project, providing a thin wrapper over its
|
||||
components.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="gemfire"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-amqp-support">
|
||||
<title>AMQP Support</title>
|
||||
<para>
|
||||
Spring Integration 2.1 adds several Channel Adapters for receiving and
|
||||
sending messages using the
|
||||
<ulink url="http://www.amqp.org/"><emphasis>Advanced Message Queuing Protocol</emphasis></ulink> (AMQP).
|
||||
Furthermore, Spring Integration also provides a point-to-point
|
||||
Message Channel, as well as a publish/subscribe Message Channel
|
||||
that are backed by AMQP Exchanges and Queues.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="amqp"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-mongodb-support">
|
||||
<title>MongoDB Support</title>
|
||||
<para>
|
||||
As of version 2.1 Spring Integration provides support for
|
||||
<ulink url="http://www.mongodb.org/">MongoDB</ulink>
|
||||
by providing a MongoDB-based MessageStore.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="mongodb"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-redis-support">
|
||||
<title>Redis Support</title>
|
||||
<para>
|
||||
As of version 2.1 Spring Integration supports
|
||||
<ulink url="http://redis.io/">Redis</ulink>, an advanced key-value
|
||||
store, by providing a Redis-based MessageStore as well as
|
||||
Publish-Subscribe Messaging adapters.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="redis"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-resource-support">
|
||||
<title>Support for Spring's Resource abstraction</title>
|
||||
<para>
|
||||
As of version 2.1, we've introduced a new <emphasis>Resource Inbound Channel Adapter</emphasis> that builds upon
|
||||
Spring's Resource abstraction to support greater flexibility across a variety of actual types of
|
||||
underlying resources, such as a file, a URL, or a class path resource. Therefore, it's similar to but
|
||||
more generic than the <emphasis>File Inbound Channel Adapter</emphasis>.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="resource-inbound-channel-adapter"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-stored-proc-support">
|
||||
<title>Stored Procedure Components</title>
|
||||
<para>
|
||||
With Spring Integration 2.1, the <code>JDBC</code> Module also provides
|
||||
Stored Procedure support by adding several new components, including
|
||||
inbound/outbound channel adapters and an Outbound Gateway. The Stored
|
||||
Procedure support leverages Spring's
|
||||
<ulink url="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/jdbc/core/simple/SimpleJdbcCall.html"><classname>SimpleJdbcCall</classname></ulink>
|
||||
class and consequently supports stored procedures for:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>Apache Derby</listitem>
|
||||
<listitem>DB2</listitem>
|
||||
<listitem>MySQL</listitem>
|
||||
<listitem>Microsoft SQL Server</listitem>
|
||||
<listitem>Oracle</listitem>
|
||||
<listitem>PostgreSQL</listitem>
|
||||
<listitem>Sybase</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
The Stored Procedure components also support Sql Functions for
|
||||
the following databases:
|
||||
</para>
|
||||
<itemizedlist>
|
||||
<listitem>MySQL</listitem>
|
||||
<listitem>Microsoft SQL Server</listitem>
|
||||
<listitem>Oracle</listitem>
|
||||
<listitem>PostgreSQL</listitem>
|
||||
</itemizedlist>
|
||||
<para>
|
||||
For further details please see <xref linkend="stored-procedures"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-xpath-filter-support">
|
||||
<title>XPath and XML Validating Filter</title>
|
||||
<para>
|
||||
Spring Integration 2.1 provides a new XPath-based Message Filter,
|
||||
that is part of the <code>XML</code> module. The XPath Filter
|
||||
allows you to filter messages using provided XPath Expressions.
|
||||
|
||||
Furthermore, documentation was added for the XML Validating Filter.
|
||||
</para>
|
||||
<para>
|
||||
For more details please see <xref linkend="xml-xpath-filter"/>
|
||||
and <xref linkend="xml-validating-filter"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-payload-enricher-support">
|
||||
<title>Payload Enricher</title>
|
||||
<para>
|
||||
Since Spring Integration 2.1, the Payload Enricher is provided. A
|
||||
Payload Enricher defines an endpoint that typically passes a
|
||||
<ulink url="http://static.springsource.org/spring-integration/api/org/springframework/integration/Message.html"><interfacename>Message</interfacename></ulink>
|
||||
to the exposed request channel and then expects a reply message.
|
||||
The reply message then becomes the root object for evaluation of
|
||||
expressions to enrich the target payload.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="payload-enricher"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-ftp-outbound-gateway">
|
||||
<title>FTP and SFTP Outbound Gateways</title>
|
||||
<para>
|
||||
Spring Integration 2.1 provides two new Outbound Gateways in order
|
||||
to interact with remote File Transfer Protocol (FTP) or
|
||||
Secure File Transfer Protocol (SFT) servers. These two gateways allow
|
||||
you to directly execute a limited set of remote commands.
|
||||
</para>
|
||||
<para>
|
||||
For instance, you can use these Outbound Gateways to list, retrieve and
|
||||
delete remote files and have the Spring Integration message flow
|
||||
continue with the remote server's response.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="ftp-outbound-gateway"/>
|
||||
and <xref linkend="sftp-outbound-gateway"/>.
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-new-ftp-session-caching">
|
||||
<title>FTP Session Caching</title>
|
||||
<para>
|
||||
As of version 2.1, we have exposed more flexibility with regards to
|
||||
session management for remote file adapters (e.g., FTP, SFTP etc).
|
||||
</para>
|
||||
<para>
|
||||
Specifically, the <code>cache-sessions</code> attribute, which is
|
||||
available via the XML namespace support, is now
|
||||
<emphasis>deprecated</emphasis>. Alternatively, we added the
|
||||
<code>sessionCacheSize</code> and <code>sessionWaitTimeout</code>
|
||||
attributes on the <classname>CachingSessionFactory</classname>.
|
||||
</para>
|
||||
<para>
|
||||
For further details please see <xref linkend="ftp-session-caching"/>
|
||||
and <xref linkend="sftp-session-caching"/>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</section>
|
||||
<section id="2.1-framework-refactorings">
|
||||
<title>Framework Refactoring</title>
|
||||
<section id="2.1-router-standardization">
|
||||
<title>Standardizing Router Configuration</title>
|
||||
<para>
|
||||
Router parameters have been standardized across all router
|
||||
implementations with Spring Integration 2.1 providing a more
|
||||
consistent user experience.
|
||||
</para>
|
||||
<para>
|
||||
With Spring Integration 2.1 the <code>ignore-channel-name-resolution-failures</code>
|
||||
attribute has been removed in favor of consolidating its behavior
|
||||
with the <code>resolution-required</code> attribute. Also,
|
||||
the <code>resolution-required</code> attribute now defaults to <code>true</code>.
|
||||
</para>
|
||||
<para>
|
||||
Starting with Spring Integration 2.1, routers will no longer silently
|
||||
drop any messages, if no default output channel was defined. This means,
|
||||
that by default routers now require at least one resolved channel (if no
|
||||
<code>default-output-channel</code> was set) and
|
||||
by default will throw a <classname>MessageDeliveryException</classname>
|
||||
if no channel was determined (or an attempt to send was not successful).
|
||||
</para>
|
||||
<para>
|
||||
If, however, you do desire to drop messages silently, simply set
|
||||
<code>default-output-channel="nullChannel"</code>.</para>
|
||||
<important>
|
||||
With the standardization of Router parameters and the consolidation
|
||||
of the parameters described above, there is the possibility of
|
||||
breaking older Spring Integration based applications.
|
||||
</important>
|
||||
<para>
|
||||
For further details please see <xref linkend="router"/>
|
||||
</para>
|
||||
</section>
|
||||
<section id="2.1-schema-updated">
|
||||
<title>XML Schemas updated to 2.1</title>
|
||||
<para>
|
||||
Spring Integration 2.1 ships with an updated XML Schema (version 2.1),
|
||||
providing many improvements, e.g. the Router standardizations
|
||||
discussed above.
|
||||
</para>
|
||||
<para>
|
||||
From now on, users <emphasis>must</emphasis> always declare the
|
||||
latest XML schema (currently version 2.1). Alternatively, they can
|
||||
use the version-less schema. Generally, the best option is to
|
||||
use version-less namespaces, as these will automatically use the
|
||||
latest available version of Spring Integration.
|
||||
</para>
|
||||
<para>
|
||||
Declaring a version-less Spring Integration namespace:
|
||||
</para>
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:int="http://www.springframework.org/schema/integration"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
...
|
||||
</beans>]]></programlisting>
|
||||
|
||||
<para>
|
||||
Declaring a Spring Integration namespace using an explicit version:
|
||||
</para>
|
||||
|
||||
<programlisting language="xml"><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:int="http://www.springframework.org/schema/integration"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration
|
||||
http://www.springframework.org/schema/integration/spring-integration.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
...
|
||||
</beans>]]></programlisting>
|
||||
|
||||
|
||||
<para>
|
||||
The old 1.0 and 2.0 schemas are still there, but if an Application
|
||||
Context still references one of those deprecated schemas, the validator
|
||||
will fail on initialization.
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
<section id="2.1-source-control-infrastructure">
|
||||
<title>Source Control Management and Build Infrastructure</title>
|
||||
<section id="2.1-move-to-github">
|
||||
<title>Source Code now hosted on Github</title>
|
||||
<para>
|
||||
Since version 2.0, the Spring Integration project uses <ulink url="http://git-scm.com/">Git</ulink> for
|
||||
version control. In order to increase community visibility even
|
||||
further, the project was moved from SpringSource hosted Git
|
||||
repositories to <ulink url="http://www.github.com/">Github</ulink>.
|
||||
The Spring Integration Git repository is located at:
|
||||
<ulink url="https://github.com/SpringSource/spring-integration/"/>
|
||||
</para>
|
||||
<para>
|
||||
For the project we also improved the process of providing code
|
||||
contributions and we ensure that every commit is peer-reviewed.
|
||||
In fact, core committers now follow the same process as contributors.
|
||||
For more details please see:
|
||||
</para>
|
||||
<para><ulink url="https://github.com/SpringSource/spring-integration/wiki/Contributor-Guidelines"/></para>
|
||||
</section>
|
||||
<section id="2.1-sonar">
|
||||
<title>Improved Source Code Visibility with Sonar</title>
|
||||
<para>
|
||||
In an effort to provide better source code visibility and consequently
|
||||
to monitor the quality of Spring Integration's source code, an instance
|
||||
of <ulink url="http://www.sonarsource.org/">Sonar</ulink> was setup
|
||||
and metrics are gathered nightly and made avaiblable at:
|
||||
</para>
|
||||
<para><ulink url="https://sonar.springsource.org/"/></para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="2.1-new-samples">
|
||||
<title>New Samples</title>
|
||||
<para>
|
||||
For the 2.1 release of Spring Integration we also expanded the Spring
|
||||
Integration Samples project and added many new samples, e.g. sampples
|
||||
covering AMQP support, the new payload enricher, a sample illustrating
|
||||
techniques for testing Spring Integration flow fragments, as well as
|
||||
an example for executing Stored Procedures against Oracle. For details
|
||||
please visit:
|
||||
</para>
|
||||
<para><ulink url="https://github.com/SpringSource/spring-integration-samples"/></para>
|
||||
</section>
|
||||
</chapter>
|
||||
134
src/reference/docbook/ws.xml
Normal file
@@ -0,0 +1,134 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="ws"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Web Services Support</title>
|
||||
|
||||
<section id="webservices-outbound">
|
||||
<title>Outbound Web Service Gateways</title>
|
||||
<para>
|
||||
To invoke a Web Service upon sending a message to a channel, there are two options - both of which build
|
||||
upon the <ulink url="http://static.springframework.org/spring-ws/sites/1.5/">Spring Web Services</ulink>
|
||||
project: <classname>SimpleWebServiceOutboundGateway</classname> and
|
||||
<classname>MarshallingWebServiceOutboundGateway</classname>. The former will accept either a
|
||||
<classname>String</classname> or <interfacename>javax.xml.transform.Source</interfacename> as the message
|
||||
payload. The latter provides support for any implementation of the <interfacename>Marshaller</interfacename>
|
||||
and <interfacename>Unmarshaller</interfacename> interfaces. Both require a Spring Web Services
|
||||
<interfacename>DestinationProvider</interfacename> for determining the URI of the Web Service to be
|
||||
called.<programlisting language="java"> simpleGateway = new SimpleWebServiceOutboundGateway(destinationProvider);
|
||||
|
||||
marshallingGateway = new MarshallingWebServiceOutboundGateway(destinationProvider, marshaller);
|
||||
</programlisting>
|
||||
<note>
|
||||
When using the namespace support described below, you will only need to set a URI. Internally, the parser
|
||||
will configure a fixed URI DestinationProvider implementation. If you do need dynamic resolution of the
|
||||
URI at runtime, however, then the DestinationProvider can provide such behavior as looking up the URI from
|
||||
a registry. See the Spring Web Services
|
||||
<ulink url="http://static.springsource.org/spring-ws/sites/1.5/apidocs/index.html">javadoc</ulink> for
|
||||
more information about the DestinationProvider strategy.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
For more detail on the inner workings, see the Spring Web Services reference guide's chapter covering
|
||||
<ulink url="http://static.springframework.org/spring-ws/site/reference/html/client.html">client access</ulink>
|
||||
as well as the chapter covering
|
||||
<ulink url="http://static.springframework.org/spring-ws/site/reference/html/oxm.html">Object/XML mapping</ulink>.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="webservices-inbound">
|
||||
<title>Inbound Web Service Gateways</title>
|
||||
<para>
|
||||
To send a message to a channel upon receiving a Web Service invocation, there are two options again: <classname>SimpleWebServiceInboundGateway</classname> and
|
||||
<classname>MarshallingWebServiceInboundGateway</classname>. The former will extract a <interfacename>javax.xml.transform.Source</interfacename>
|
||||
from the <classname>WebServiceMessage</classname> and set it as the message
|
||||
payload. The latter provides support for implementation of the <interfacename>Marshaller</interfacename>
|
||||
and <interfacename>Unmarshaller</interfacename> interfaces.
|
||||
If the incoming web service message is a SOAP message the SOAP Action header will be added to the headers of the
|
||||
<classname>Message</classname> that is forwarded onto the request channel.
|
||||
|
||||
<programlisting language="java"> simpleGateway = new SimpleWebServiceInboundGateway();
|
||||
simpleGateway.setRequestChannel(forwardOntoThisChannel);
|
||||
simpleGateway.setReplyChannel(listenForResponseHere); //Optional
|
||||
|
||||
marshallingGateway = new MarshallingWebServiceInboundGateway(marshaller);
|
||||
//set request and optionally reply channel
|
||||
</programlisting>
|
||||
Both gateways implement the Spring Web Services <interfacename>MessageEndpoint</interfacename>
|
||||
interface, so they can be configured with a <classname>MessageDispatcherServlet</classname>
|
||||
as per standard Spring Web Services configuration.
|
||||
</para>
|
||||
<para>
|
||||
For more detail on how to use these components, see the Spring Web Services reference guide's chapter covering
|
||||
<ulink url="http://static.springframework.org/spring-ws/sites/1.5/reference/html/server.html">creating a Web Service</ulink>.
|
||||
The chapter covering
|
||||
<ulink url="http://static.springframework.org/spring-ws/site/reference/html/oxm.html">Object/XML mapping</ulink> is also applicable again.
|
||||
</para>
|
||||
</section>
|
||||
<section id="webservices-namespace">
|
||||
<title>Web Service Namespace Support</title>
|
||||
<para>
|
||||
To configure an outbound Web Service Gateway, use the "outbound-gateway" element from the "ws" namespace:
|
||||
<programlisting language="xml"><![CDATA[<int-ws:outbound-gateway id="simpleGateway"
|
||||
request-channel="inputChannel"
|
||||
uri="http://example.org"/>]]></programlisting>
|
||||
<note>
|
||||
Notice that this example does not provide a 'reply-channel'. If the Web Service were to
|
||||
return a non-empty response, the Message containing that response would be sent to the
|
||||
reply channel provided in the request Message's REPLY_CHANNEL header, and if that were
|
||||
not available a channel resolution Exception would be thrown. If you want to send the
|
||||
reply to another channel instead, then provide a 'reply-channel' attribute on the
|
||||
'outbound-gateway' element.
|
||||
</note>
|
||||
<tip>
|
||||
When invoking a Web Service that returns an empty response after using a String payload
|
||||
for the request Message, <emphasis>no reply Message will be sent by default</emphasis>.
|
||||
Therefore you don't need to set a 'reply-channel' or have a REPLY_CHANNEL header in the
|
||||
request Message. If for any reason you actually <emphasis>do</emphasis> want to receive
|
||||
the empty response as a Message, then provide the 'ignore-empty-responses' attribute with
|
||||
a value of <emphasis>false</emphasis> (this only applies for Strings, because using a
|
||||
Source or Document object simply leads to a NULL response and will therefore
|
||||
<emphasis>never</emphasis> generate a reply Message).
|
||||
</tip>
|
||||
|
||||
To set up an inbound Web Service Gateway, use the "inbound-gateway":
|
||||
<programlisting language="xml"><![CDATA[<int-ws:inbound-gateway id="simpleGateway"
|
||||
request-channel="inputChannel"/>]]></programlisting>
|
||||
|
||||
To use Spring OXM Marshallers and/or Unmarshallers, provide bean references. For outbound:
|
||||
<programlisting language="xml"><![CDATA[<int-ws:outbound-gateway id="marshallingGateway"
|
||||
request-channel="requestChannel"
|
||||
uri="http://example.org"
|
||||
marshaller="someMarshaller"
|
||||
unmarshaller="someUnmarshaller"/>]]></programlisting>
|
||||
And for inbound:
|
||||
<programlisting language="xml"><![CDATA[<int-ws:inbound-gateway id="marshallingGateway"
|
||||
request-channel="requestChannel"
|
||||
marshaller="someMarshaller"
|
||||
unmarshaller="someUnmarshaller"/>]]></programlisting>
|
||||
|
||||
<note>
|
||||
Most <interfacename>Marshaller</interfacename> implementations also implement the
|
||||
<interfacename>Unmarshaller</interfacename> interface. When using such a
|
||||
<interfacename>Marshaller</interfacename>, only the "marshaller"
|
||||
attribute is necessary. Even when using a <interfacename>Marshaller</interfacename>,
|
||||
you may also provide a reference for the "request-callback" on the outbound gateways.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
For either outbound gateway type, a "destination-provider" attribute can be specified instead of the "uri"
|
||||
(exactly one of them is required). You can then reference any Spring Web Services DestinationProvider
|
||||
implementation (e.g. to lookup the URI at runtime from a registry).
|
||||
</para>
|
||||
<para>
|
||||
For either outbound gateway type, the "message-factory" attribute can also be configured with a reference to any
|
||||
Spring Web Services <interfacename>WebServiceMessageFactory</interfacename> implementation.
|
||||
</para>
|
||||
<para>
|
||||
For the simple inbound gateway type, the "extract-payload" attribute can be set to false to forward
|
||||
the entire <interfacename>WebServiceMessage</interfacename> instead of just its payload as a
|
||||
<interfacename>Message</interfacename> to the request channel. This might be useful, for example,
|
||||
when a custom Transformer works against the <interfacename>WebServiceMessage</interfacename> directly.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||
1034
src/reference/docbook/xml.xml
Normal file
262
src/reference/docbook/xmpp.xml
Normal file
@@ -0,0 +1,262 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="xmpp"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>XMPP Support</title>
|
||||
<para>
|
||||
Spring Integration provides Channel Adapters for <ulink url="http://www.xmpp.org">XMPP</ulink>.
|
||||
</para>
|
||||
<section id="xmpp-intro">
|
||||
<title>Introduction</title>
|
||||
<para>
|
||||
XMPP describes a way for multiple agents to communicate with each other in a distributed system.
|
||||
The canonical use case is to send and receive chat messages, though XMPP can be, and is, used for far more
|
||||
applications.
|
||||
XMPP is used to describe a network of actors. Within that network, actors may address each other directly, as well
|
||||
as broadcast status changes (e.g. "presence").
|
||||
</para>
|
||||
<para>
|
||||
XMPP provides the messaging fabric that underlies some of the biggest Instant Messaging networks in the world,
|
||||
including Google Talk (GTalk) - which is also available from within GMail - and Facebook Chat.
|
||||
There are many good open-source XMPP servers available. Two popular implementations are
|
||||
<ulink url="http://www.igniterealtime.org/projects/openfire/">
|
||||
<citetitle>Openfire</citetitle>
|
||||
</ulink>
|
||||
and
|
||||
<ulink url="http://www.ejabberd.im">
|
||||
<citetitle>ejabberd</citetitle>
|
||||
</ulink>
|
||||
</para>
|
||||
<para>
|
||||
Spring integration provides support for XMPP via XMPP adapters which support sending and receiving both XMPP chat messages and
|
||||
presence changes from other entries in your roster. As with other adapters, the XMPP adapters come with support for a
|
||||
convenient namespace-based configuration.
|
||||
To configure the XMPP namespace, include the following elements in the headers of your XML configuration file:
|
||||
|
||||
<programlisting language="xml"><![CDATA[xmlns:int-xmpp="http://www.springframework.org/schema/integration/xmpp"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/integration/xmpp
|
||||
http://www.springframework.org/schema/integration/xmpp/spring-integration-xmpp.xsd"]]></programlisting>
|
||||
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="xmpp-connection">
|
||||
<title>XMPP Connection</title>
|
||||
<para>
|
||||
Before using inbound or outbound XMPP adapters to participate in the XMPP network, an actor must establish its XMPP connection. This
|
||||
connection object could be shared by all XMPP adapters connected to a particular account. Typically this requires - at a minimum -
|
||||
<code>user</code>, <code>password</code>, and <code>host</code>.
|
||||
|
||||
To create a basic XMPP connection, you can utilize the convenience of the namespace.
|
||||
|
||||
<programlisting lang="xml"><![CDATA[<int-xmpp:xmpp-connection
|
||||
id="myConnection"
|
||||
user="user"
|
||||
password="password"
|
||||
host="host"
|
||||
port="port"
|
||||
resource="theNameOfTheResource"
|
||||
subscription-mode="accept_all"/>
|
||||
]]></programlisting>
|
||||
</para>
|
||||
|
||||
<para>
|
||||
<note>
|
||||
For added convenience you can rely on the default naming convention and omit the <code>id</code> attribute.
|
||||
The default name <emphasis>xmppConnection</emphasis> will be used for this connection bean.
|
||||
</note>
|
||||
</para>
|
||||
<para>
|
||||
If the XMPP Connection goes stale, reconnection attempts will be made with an automatic login as long as the previous connection
|
||||
state was logged (authenticated). We also register a <classname>ConnectionListener</classname> which will log connection events
|
||||
if the DEBUG logging level is enabled.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="xmpp-messages">
|
||||
<title>XMPP Messages</title>
|
||||
<section id="xmpp-message-inbound-channel-adapter">
|
||||
<title>Inbound Message Channel Adapter</title>
|
||||
<para>The Spring Integration adapters support receiving chat messages from other users in the system. To do this, the
|
||||
<emphasis>Inbound Message Channel Adapter</emphasis> "logs in" as a user on your behalf and receives the messages sent to that user. Those messages are then
|
||||
forwarded to your Spring Integration client.
|
||||
The payload of the inbound Spring Integration message may be of the raw type<classname>
|
||||
org.jivesoftware.smack.packet.Message</classname>, or of the type
|
||||
<classname>java.lang.String</classname> if you set the <code>extract-payload</code> attribute's value to 'true'
|
||||
when configuring an adapter.
|
||||
Configuration support for the XMPP <emphasis>Inbound Message Channel Adapter</emphasis> is provided via the <code>inbound-channel-adapter</code> element.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-xmpp:inbound-channel-adapter id="xmppInboundAdapter"
|
||||
channel="xmppInbound"
|
||||
xmpp-connection="testConnection"
|
||||
extract-payload="false"
|
||||
auto-startup="true"/>]]></programlisting>
|
||||
|
||||
As you can see amongst the usual attributes this adapter also requires a reference to an XMPP Connection.
|
||||
</para>
|
||||
<para>
|
||||
It is also important to mention that the XMPP inbound adapter is an <emphasis>event driven adapter</emphasis>
|
||||
and a <classname>Lifecycle</classname> implementation.
|
||||
When started it will register a <classname>PacketListener</classname> that will listen for incoming XMPP Chat Messages.
|
||||
It forwards any received messages to the underlying adapter which will convert them to Spring Integration Messages and
|
||||
send them to the specified <classname>channel</classname>. It will unregister the <classname>PacketListener</classname>
|
||||
when it is stopped.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
|
||||
<section id="xmpp-message-outbound-channel-adapter">
|
||||
<title>Outbound Message Channel Adapter</title>
|
||||
|
||||
<para>
|
||||
You may also send chat messages to other users on XMPP using the <emphasis>Outbound Message Channel Adapter</emphasis>.
|
||||
Configuration support for the XMPP <emphasis>Outbound Message Channel Adapter</emphasis> is provided via the <code>outbound-channel-adapter</code> element.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-xmpp:outbound-channel-adapter id="outboundEventAdapter"
|
||||
channel="outboundEventChannel"
|
||||
xmpp-connection="testConnection"/>]]></programlisting>
|
||||
|
||||
The adapter expects as its input - at a minimum - a payload of type <classname>java.lang.String</classname>, and a header value
|
||||
for <classname>XmppHeaders.CHAT_TO</classname> that specifies to which user the Message should be sent.
|
||||
To create a message you might use the following Java code:
|
||||
|
||||
<programlisting language="java"><![CDATA[Message<String> xmppOutboundMsg = MessageBuilder.withPayload("Hello, XMPP!" )
|
||||
.setHeader(XmppHeaders.CHAT_TO, "userhandle")
|
||||
.build();]]></programlisting>
|
||||
|
||||
Another mechanism of setting the header is by using the XMPP header-enricher support. Here is an example.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-xmpp:header-enricher input-channel="input" output-channel="output">
|
||||
<int-xmpp:chat-to value="test1@example.org"/>
|
||||
</int-xmpp:header-enricher>]]></programlisting>
|
||||
</para>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<section id="xmpp-presence">
|
||||
<title>XMPP Presence</title>
|
||||
|
||||
<para>
|
||||
XMPP also supports broadcasting state. You can use this capability to
|
||||
let people who have you on their roster see your state changes. This happens all the time with your IM clients; you
|
||||
change your away status, and then set an away message, and everybody who has you on their roster sees your icon or username
|
||||
change to reflect this new state, and additionally might see your new "away" message.
|
||||
If you would like to receive notification, or notify others, of state changes, you can use Spring Integration's "presence" adapters.
|
||||
</para>
|
||||
|
||||
<section id="xmpp-roster-inbound-channel-adapter">
|
||||
<title>Inbound Presence Message Channel Adapter</title>
|
||||
<para>
|
||||
Spring Integration provides an <emphasis>Inbound Presence Message Channel Adapter</emphasis> which supports receiving Presence
|
||||
events from other users in the system who happen to be on your Roster. To do this, the adapter "logs in" as a user
|
||||
on your behalf, registers a <classname>RosterListener</classname> and forwards received Presence update events as Messages to the channel
|
||||
identified by the <code>channel</code> attribute. The payload of the Message will be a <classname>org.jivesoftware.smack.packet.Presence</classname>
|
||||
object (see http://www.igniterealtime.org/builds/smack/docs/3.1.0/javadoc/org/jivesoftware/smack/packet/Presence.html).
|
||||
</para>
|
||||
<para>
|
||||
Configuration support for the XMPP <emphasis>Inbound Presence Message Channel Adapter</emphasis> is provided via
|
||||
the <code>presence-inbound-channel-adapter</code> element.
|
||||
<programlisting language="xml"><![CDATA[<int-xmpp:presence-inbound-channel-adapter channel="outChannel"
|
||||
xmpp-connection="testConnection" auto-startup="false"/>]]></programlisting>
|
||||
|
||||
As you can see amongst the usual attributes this adapter also requires a reference to an XMPP Connection.
|
||||
It is also important to mention that this adapter is an event driven adapter and a <classname>Lifecycle</classname> implementation.
|
||||
It will register a <classname>RosterListener</classname> when started and will unregister that <classname>RosterListener</classname>
|
||||
when stopped.
|
||||
</para>
|
||||
</section>
|
||||
|
||||
<section id="xmpp-roster-outbound-channel-adapter">
|
||||
<title>Outbound Presence Message Channel Adapter</title>
|
||||
|
||||
<para>
|
||||
Spring Integration also supports sending Presence events to be seen by other users in the network who happen to have you on their
|
||||
Roster. When you send a Message to the <emphasis>Outbound Presence Message Channel Adapter</emphasis> it extracts the payload,
|
||||
which is expected to be of type <classname>org.jivesoftware.smack.packet.Presence</classname>
|
||||
(see http://www.igniterealtime.org/builds/smack/docs/3.1.0/javadoc/org/jivesoftware/smack/packet/Presence.html) and sends it to
|
||||
the XMPP Connection, thus advertising your presence events to the rest of the network.
|
||||
</para>
|
||||
<para>
|
||||
Configuration support for the XMPP <emphasis>Outbound Presence Message Channel Adapter</emphasis> is provided via
|
||||
the <code>presence-outbound-channel-adapter</code> element.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-xmpp:presence-outbound-channel-adapter id="eventOutboundPresenceChannel"
|
||||
xmpp-connection="testConnection"/>]]></programlisting>
|
||||
|
||||
It can also be a <emphasis>Polling Consumer</emphasis> (if it receives Messages from a Pollable Channel) in which case you would
|
||||
need to register a Poller.
|
||||
|
||||
<programlisting language="xml"><![CDATA[<int-xmpp:presence-outbound-channel-adapter id="pollingOutboundPresenceAdapter"
|
||||
xmpp-connection="testConnection"
|
||||
channel="pollingChannel">
|
||||
<int:poller fixed-rate="1000" max-messages-per-poll="1"/>
|
||||
</int-xmpp:presence-outbound-channel-adapter>]]></programlisting>
|
||||
|
||||
Like its inbound counterpart, it requires a reference to an XMPP Connection.
|
||||
</para>
|
||||
</section>
|
||||
<para>
|
||||
<note>
|
||||
If you are relying on the default naming convention for an XMPP Connection bean (described earlier), and you have only one
|
||||
XMPP Connection bean configured in your Application Context, you may omit the <code>xmpp-connection</code> attribute.
|
||||
In that case, the bean with the name <emphasis>xmppConnection</emphasis> will be located and injected into the adapter.
|
||||
</note>
|
||||
</para>
|
||||
</section>
|
||||
<section id="xmpp-appendices">
|
||||
<title>Appendices</title>
|
||||
|
||||
<para>
|
||||
Since Spring Integration XMPP support is based on the Smack 3.1 API (http://www.igniterealtime.org/downloads/index.jsp), it is important
|
||||
to know a few details related to more complex configuration of the XMPP Connection object.
|
||||
</para>
|
||||
<para>
|
||||
As stated earlier the <code>xmpp-connection</code> namespace support is designed to simplify basic connection configuration and
|
||||
only supports a few common configuration attributes. However, the <classname>org.jivesoftware.smack.ConnectionConfiguration</classname>
|
||||
object defines about 20 attributes, and there is no real value of adding namespace support for all of them. So, for more complex connection
|
||||
configurations, simply configure an instance of our <classname>XmppConnectionFactoryBean</classname> as a regular bean, and inject a
|
||||
<classname>org.jivesoftware.smack.ConnectionConfiguration</classname> as a constructor argument to that FactoryBean. Every property
|
||||
you need, can be specified directly on that ConnectionConfiguration instance (a bean definition with the 'p' namespace would work well).
|
||||
This way SSL, or any other attributes, could be set directly. Here's an example:
|
||||
|
||||
<programlisting language="xml"><![CDATA[<bean id="xmppConnection" class="org.springframework.integration.xmpp.XmppConnectionFactoryBean">
|
||||
<constructor-arg>
|
||||
<bean class="org.jivesoftware.smack.ConnectionConfiguration">
|
||||
<constructor-arg value="myServiceName"/>
|
||||
<property name="truststorePath" value="..."/>
|
||||
<property name="socketFactory" ref="..."/>
|
||||
</bean>
|
||||
</constructor-arg>
|
||||
</bean>
|
||||
<int:channel id="outboundEventChannel"/>
|
||||
|
||||
<int-xmpp:outbound-channel-adapter id="outboundEventAdapter"
|
||||
channel="outboundEventChannel"
|
||||
xmpp-connection="xmppConnection"/>]]></programlisting>
|
||||
</para>
|
||||
<para>
|
||||
Another important aspect of the Smack API is static initializers. For more complex cases (e.g., registering a SASL Mechanism), you may need
|
||||
to execute certain static initializers. One of those static initializers is <classname>SASLAuthentication</classname>, which allows
|
||||
you to register supported SASL mechanisms. For that level of complexity, we would recommend Spring JavaConfig-style of the XMPP Connection
|
||||
configuration. Then, you can configure the entire component through Java code and execute all other necessary Java code including
|
||||
static initializers at the appropriate time.
|
||||
|
||||
<programlisting language="java"><![CDATA[@Configuration
|
||||
public class CustomConnectionConfiguration {
|
||||
@Bean
|
||||
public XMPPConnection xmppConnection() {
|
||||
SASLAuthentication.supportSASLMechanism("EXTERNAL", 0); // static initializer
|
||||
|
||||
ConnectionConfiguration config = new ConnectionConfiguration("localhost", 5223);
|
||||
config.setTrustorePath("path_to_truststore.jks");
|
||||
config.setSecurityEnabled(true);
|
||||
config.setSocketFactory(SSLSocketFactory.getDefault());
|
||||
return new XMPPConnection(config);
|
||||
}
|
||||
}]]></programlisting>
|
||||
For more information on the JavaConfig style of Application Context configuration, refer to the following section in the Spring Reference Manual:
|
||||
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java
|
||||
</para>
|
||||
</section>
|
||||
|
||||
</chapter>
|
||||