4524 lines
216 KiB
HTML
4524 lines
216 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<meta name="generator" content="Asciidoctor 1.5.7.1">
|
||
<title>Preface</title>
|
||
<link rel="stylesheet" href="css/spring.css">
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
|
||
|
||
<style>
|
||
.hidden {
|
||
display: none;
|
||
}
|
||
|
||
.switch {
|
||
border-width: 1px 1px 0 1px;
|
||
border-style: solid;
|
||
border-color: #7a2518;
|
||
display: inline-block;
|
||
}
|
||
|
||
.switch--item {
|
||
padding: 10px;
|
||
background-color: #ffffff;
|
||
color: #7a2518;
|
||
display: inline-block;
|
||
cursor: pointer;
|
||
}
|
||
|
||
.switch--item:not(:first-child) {
|
||
border-width: 0 0 0 1px;
|
||
border-style: solid;
|
||
border-color: #7a2518;
|
||
}
|
||
|
||
.switch--item.selected {
|
||
background-color: #7a2519;
|
||
color: #ffffff;
|
||
}
|
||
</style>
|
||
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
|
||
<script type="text/javascript">
|
||
function addBlockSwitches() {
|
||
$('.primary').each(function() {
|
||
primary = $(this);
|
||
createSwitchItem(primary, createBlockSwitch(primary)).item.addClass("selected");
|
||
primary.children('.title').remove();
|
||
});
|
||
$('.secondary').each(function(idx, node) {
|
||
secondary = $(node);
|
||
primary = findPrimary(secondary);
|
||
switchItem = createSwitchItem(secondary, primary.children('.switch'));
|
||
switchItem.content.addClass('hidden');
|
||
findPrimary(secondary).append(switchItem.content);
|
||
secondary.remove();
|
||
});
|
||
}
|
||
|
||
function createBlockSwitch(primary) {
|
||
blockSwitch = $('<div class="switch"></div>');
|
||
primary.prepend(blockSwitch);
|
||
return blockSwitch;
|
||
}
|
||
|
||
function findPrimary(secondary) {
|
||
candidate = secondary.prev();
|
||
while (!candidate.is('.primary')) {
|
||
candidate = candidate.prev();
|
||
}
|
||
return candidate;
|
||
}
|
||
|
||
function createSwitchItem(block, blockSwitch) {
|
||
blockName = block.children('.title').text();
|
||
content = block.children('.content').first().append(block.next('.colist'));
|
||
item = $('<div class="switch--item">' + blockName + '</div>');
|
||
item.on('click', '', content, function(e) {
|
||
$(this).addClass('selected');
|
||
$(this).siblings().removeClass('selected');
|
||
e.data.siblings('.content').addClass('hidden');
|
||
e.data.removeClass('hidden');
|
||
});
|
||
blockSwitch.append(item);
|
||
return {'item': item, 'content': content};
|
||
}
|
||
|
||
$(addBlockSwitches);
|
||
</script>
|
||
|
||
</head>
|
||
<body class="book toc2 toc-left">
|
||
<div id="header">
|
||
<div id="toc" class="toc2">
|
||
<div id="toctitle">Table of Contents</div>
|
||
<ul class="sectlevel1">
|
||
<li><a href="#spring-cloud-stream-reference">Preface</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_a_brief_history_of_springs_data_integration_journey">A Brief History of Spring’s Data Integration Journey</a></li>
|
||
<li><a href="#_quick_start">Quick Start</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#spring-cloud-stream-preface-creating-sample-application">Creating a Sample Application by Using Spring Initializr</a></li>
|
||
<li><a href="#spring-cloud-stream-preface-importing-project">Importing the Project into Your IDE</a></li>
|
||
<li><a href="#spring-cloud-stream-preface-adding-message-handler">Adding a Message Handler, Building, and Running</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_whats_new_in_2_2">What’s New in 2.2?</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#spring-cloud-stream-preface-new-features">New Features and Components</a></li>
|
||
<li><a href="#spring-cloud-stream-preface-notable-enhancements">Notable Enhancements</a></li>
|
||
<li><a href="#spring-cloud-stream-preface-notable-deprecations">Notable Deprecations</a></li>
|
||
<li><a href="#_notes_on_migrating_from_1_x_to_2_x">Notes on migrating from 1.x to 2.x?</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#spring-cloud-stream-overview-introducing">Introducing Spring Cloud Stream</a></li>
|
||
<li><a href="#_main_concepts">Main Concepts</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#spring-cloud-stream-overview-application-model">Application Model</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_fat_jar">Fat JAR</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#spring-cloud-stream-overview-binder-abstraction">The Binder Abstraction</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-persistent-publish-subscribe-support">Persistent Publish-Subscribe Support</a></li>
|
||
<li><a href="#consumer-groups">Consumer Groups</a></li>
|
||
<li><a href="#consumer-types">Consumer Types</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#durability">Durability</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#partitioning">Partitioning Support</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_programming_model">Programming Model</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_destination_binders">Destination Binders</a></li>
|
||
<li><a href="#_destination_bindings">Destination Bindings</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-producing-consuming-messages">Producing and Consuming Messages</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_spring_integration_support">Spring Integration Support</a></li>
|
||
<li><a href="#_using_streamlistener_annotation">Using @StreamListener Annotation</a></li>
|
||
<li><a href="#_using_streamlistener_for_content_based_routing">Using @StreamListener for Content-based routing</a></li>
|
||
<li><a href="#spring_cloud_function">Spring Cloud Function support</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#_overview">Overview</a></li>
|
||
<li><a href="#_reactive_functions_support">Reactive Functions support</a></li>
|
||
<li><a href="#_functional_composition">Functional Composition</a></li>
|
||
<li><a href="#_batch_consumers">Batch Consumers</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#spring-cloud-streams-overview-using-polled-consumers">Using Polled Consumers</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#_overview_2">Overview</a></li>
|
||
<li><a href="#polled-errors">Handling Errors</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#spring-cloud-stream-overview-error-handling">Error Handling</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_application_error_handling">Application Error Handling</a></li>
|
||
<li><a href="#_system_error_handling">System Error Handling</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#_drop_failed_messages">Drop Failed Messages</a></li>
|
||
<li><a href="#_dlq_dead_letter_queue">DLQ - Dead Letter Queue</a></li>
|
||
<li><a href="#_re_queue_failed_messages">Re-queue Failed Messages</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_retry_template">Retry Template</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#spring-cloud-stream-overview-binders">Binders</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_producers_and_consumers">Producers and Consumers</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-binder-api">Binder SPI</a></li>
|
||
<li><a href="#_binder_detection">Binder Detection</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_classpath_detection">Classpath Detection</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#multiple-binders">Multiple Binders on the Classpath</a></li>
|
||
<li><a href="#multiple-systems">Connecting to Multiple Systems</a></li>
|
||
<li><a href="#binding_visualization_control">Binding visualization and control</a></li>
|
||
<li><a href="#_binder_configuration_properties">Binder Configuration Properties</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_configuration_options">Configuration Options</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_binding_service_properties">Binding Service Properties</a></li>
|
||
<li><a href="#binding-properties">Binding Properties</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_common_binding_properties">Common Binding Properties</a></li>
|
||
<li><a href="#_consumer_properties">Consumer Properties</a></li>
|
||
<li><a href="#_advanced_consumer_configuration">Advanced Consumer Configuration</a></li>
|
||
<li><a href="#_producer_properties">Producer Properties</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#dynamicdestination">Using Dynamically Bound Destinations</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#content-type-management">Content Type Negotiation</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_mechanics">Mechanics</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_content_type_versus_argument_type">Content Type versus Argument Type</a></li>
|
||
<li><a href="#_message_converters">Message Converters</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_provided_messageconverters">Provided MessageConverters</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-user-defined-message-converters">User-defined Message Converters</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#schema-evolution">Schema Evolution Support</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_schema_registry_client">Schema Registry Client</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_schema_registry_client_properties">Schema Registry Client Properties</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_avro_schema_registry_client_message_converters">Avro Schema Registry Client Message Converters</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_avro_schema_registry_message_converter_properties">Avro Schema Registry Message Converter Properties</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_apache_avro_message_converters">Apache Avro Message Converters</a></li>
|
||
<li><a href="#_converters_with_schema_support">Converters with Schema Support</a></li>
|
||
<li><a href="#_schema_registry_server">Schema Registry Server</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_schema_registry_server_api">Schema Registry Server API</a>
|
||
<ul class="sectlevel4">
|
||
<li><a href="#spring-cloud-stream-overview-registering-new-schema">Registering a New Schema</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-retrieve-schema-subject-format-version">Retrieving an Existing Schema by Subject, Format, and Version</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-retrieve-schema-subject-format">Retrieving an Existing Schema by Subject and Format</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-retrieve-schema-id">Retrieving an Existing Schema by ID</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-deleting-schema-subject-format-version">Deleting a Schema by Subject, Format, and Version</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-deleting-schema-id">Deleting a Schema by ID</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-deleting-schema-subject">Deleting a Schema by Subject</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_using_confluents_schema_registry">Using Confluent’s Schema Registry</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_schema_registration_and_resolution">Schema Registration and Resolution</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#spring-cloud-stream-overview-schema-registration-process">Schema Registration Process (Serialization)</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-schema-resolution-process">Schema Resolution Process (Deserialization)</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_inter_application_communication">Inter-Application Communication</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#spring-cloud-stream-overview-connecting-multiple-application-instances">Connecting Multiple Application Instances</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-instance-index-instance-count">Instance Index and Instance Count</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-partitioning">Partitioning</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#spring-cloud-stream-overview-configuring-output-bindings-partitioning">Configuring Output Bindings for Partitioning</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-configuring-input-bindings-partitioning">Configuring Input Bindings for Partitioning</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_testing">Testing</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_disabling_the_test_binder_autoconfiguration">Disabling the Test Binder Autoconfiguration</a></li>
|
||
<li><a href="#spring_integration_test_binder">Spring Integration Test Binder</a>
|
||
<ul class="sectlevel3">
|
||
<li><a href="#_spring_integration_test_binder_and_pollablemessagesource">Spring Integration Test Binder and PollableMessageSource</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_health_indicator">Health Indicator</a></li>
|
||
<li><a href="#spring-cloud-stream-overview-metrics-emitter">Metrics Emitter</a></li>
|
||
<li><a href="#_samples">Samples</a>
|
||
<ul class="sectlevel2">
|
||
<li><a href="#_deploying_stream_applications_on_cloudfoundry">Deploying Stream Applications on CloudFoundry</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#_binder_implementations">Binder Implementations</a></li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div id="content">
|
||
<div id="preamble">
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p><strong>3.0.0.M3</strong></p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="spring-cloud-stream-reference"><a class="link" href="#spring-cloud-stream-reference">Preface</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="sect2">
|
||
<h3 id="_a_brief_history_of_springs_data_integration_journey"><a class="link" href="#_a_brief_history_of_springs_data_integration_journey">A Brief History of Spring’s Data Integration Journey</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring’s journey on Data Integration started with <a href="https://projects.spring.io/spring-integration/">Spring Integration</a>. With its programming model, it provided a consistent developer experience to build applications that can embrace <a href="http://www.enterpriseintegrationpatterns.com/">Enterprise Integration Patterns</a> to connect with external systems such as, databases, message brokers, and among others.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Fast forward to the cloud-era, where microservices have become prominent in the enterprise setting. <a href="https://projects.spring.io/spring-boot/">Spring Boot</a> transformed the way how developers built Applications. With Spring’s programming model and the runtime responsibilities handled by Spring Boot, it became seamless to develop stand-alone, production-grade Spring-based microservices.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To extend this to Data Integration workloads, Spring Integration and Spring Boot were put together into a new project. Spring Cloud Stream was born.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With Spring Cloud Stream, developers can:<br>
|
||
* Build, test, iterate, and deploy data-centric applications in isolation.<br>
|
||
* Apply modern microservices architecture patterns, including composition through messaging.<br>
|
||
* Decouple application responsibilities with event-centric thinking. An event can represent something that has happened in time, to which the downstream consumer applications can react without knowing where it originated or the producer’s identity.<br>
|
||
* Port the business logic onto message brokers (such as RabbitMQ, Apache Kafka, Amazon Kinesis).<br>
|
||
* Interoperate between channel-based and non-channel-based application binding scenarios to support stateless and stateful computations by using Project Reactor’s Flux and Kafka Streams APIs.<br>
|
||
* Rely on the framework’s automatic content-type support for common use-cases. Extending to different data conversion types is possible.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_quick_start"><a class="link" href="#_quick_start">Quick Start</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can try Spring Cloud Stream in less then 5 min even before you jump into any details by following this three-step guide.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>We show you how to create a Spring Cloud Stream application that receives messages coming from the messaging middleware of your choice (more on this later) and logs received messages to the console.
|
||
We call it <code>LoggingConsumer</code>.
|
||
While not very practical, it provides a good introduction to some of the main concepts
|
||
and abstractions, making it easier to digest the rest of this user guide.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The three steps are as follows:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-preface-creating-sample-application">Creating a Sample Application by Using Spring Initializr</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-preface-importing-project">Importing the Project into Your IDE</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-preface-adding-message-handler">Adding a Message Handler, Building, and Running</a></p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-stream-preface-creating-sample-application"><a class="link" href="#spring-cloud-stream-preface-creating-sample-application">Creating a Sample Application by Using Spring Initializr</a></h4>
|
||
<div class="paragraph">
|
||
<p>To get started, visit the <a href="https://start.spring.io">Spring Initializr</a>. From there, you can generate our <code>LoggingConsumer</code> application. To do so:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>In the <strong>Dependencies</strong> section, start typing <code>stream</code>.
|
||
When the “Cloud Stream” option should appears, select it.</p>
|
||
</li>
|
||
<li>
|
||
<p>Start typing either 'kafka' or 'rabbit'.</p>
|
||
</li>
|
||
<li>
|
||
<p>Select “Kafka” or “RabbitMQ”.</p>
|
||
<div class="paragraph">
|
||
<p>Basically, you choose the messaging middleware to which your application binds.
|
||
We recommend using the one you have already installed or feel more comfortable with installing and running.
|
||
Also, as you can see from the Initilaizer screen, there are a few other options you can choose.
|
||
For example, you can choose Gradle as your build tool instead of Maven (the default).</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>In the <strong>Artifact</strong> field, type 'logging-consumer'.</p>
|
||
<div class="paragraph">
|
||
<p>The value of the <strong>Artifact</strong> field becomes the application name.
|
||
If you chose RabbitMQ for the middleware, your Spring Initializr should now be as follows:</p>
|
||
</div>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/spring-initializr.png" alt="spring initializr">
|
||
</div>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>Click the <strong>Generate Project</strong> button.</p>
|
||
<div class="paragraph">
|
||
<p>Doing so downloads the zipped version of the generated project to your hard drive.</p>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p>Unzip the file into the folder you want to use as your project directory.</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="admonitionblock tip">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-tip" title="Tip"></i>
|
||
</td>
|
||
<td class="content">
|
||
We encourage you to explore the many possibilities available in the Spring Initializr.
|
||
It lets you create many different kinds of Spring applications.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-stream-preface-importing-project"><a class="link" href="#spring-cloud-stream-preface-importing-project">Importing the Project into Your IDE</a></h4>
|
||
<div class="paragraph">
|
||
<p>Now you can import the project into your IDE.
|
||
Keep in mind that, depending on the IDE, you may need to follow a specific import procedure.
|
||
For example, depending on how the project was generated (Maven or Gradle), you may need to follow specific import procedure (for example, in Eclipse or STS, you need to use File → Import → Maven → Existing Maven Project).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Once imported, the project must have no errors of any kind. Also, <code>src/main/java</code> should contain <code>com.example.loggingconsumer.LoggingConsumerApplication</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Technically, at this point, you can run the application’s main class.
|
||
It is already a valid Spring Boot application.
|
||
However, it does not do anything, so we want to add some code.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-stream-preface-adding-message-handler"><a class="link" href="#spring-cloud-stream-preface-adding-message-handler">Adding a Message Handler, Building, and Running</a></h4>
|
||
<div class="paragraph">
|
||
<p>Modify the <code>com.example.loggingconsumer.LoggingConsumerApplication</code> class to look as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableBinding(Sink.class)
|
||
public class LoggingConsumerApplication {
|
||
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(LoggingConsumerApplication.class, args);
|
||
}
|
||
|
||
@StreamListener(Sink.INPUT)
|
||
public void handle(Person person) {
|
||
System.out.println("Received: " + person);
|
||
}
|
||
|
||
public static class Person {
|
||
private String name;
|
||
public String getName() {
|
||
return name;
|
||
}
|
||
public void setName(String name) {
|
||
this.name = name;
|
||
}
|
||
public String toString() {
|
||
return this.name;
|
||
}
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As you can see from the preceding listing:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>We have enabled <code>Sink</code> binding (input-no-output) by using <code>@EnableBinding(Sink.class)</code>.
|
||
Doing so signals to the framework to initiate binding to the messaging middleware, where it automatically creates the destination (that is, queue, topic, and others) that are bound to the <code>Sink.INPUT</code> channel.</p>
|
||
</li>
|
||
<li>
|
||
<p>We have added a <code>handler</code> method to receive incoming messages of type <code>Person</code>.
|
||
Doing so lets you see one of the core features of the framework: It tries to automatically convert incoming message payloads to type <code>Person</code>.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You now have a fully functional Spring Cloud Stream application that does listens for messages.
|
||
From here, for simplicity, we assume you selected RabbitMQ in <a href="#spring-cloud-stream-preface-creating-sample-application">step one</a>.
|
||
Assuming you have RabbitMQ installed and running, you can start the application by running its <code>main</code> method in your IDE.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You should see following output:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code> --- [ main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: input.anonymous.CbMIwdkJSBO1ZoPDOtHtCg, bound to: input
|
||
--- [ main] o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [localhost:5672]
|
||
--- [ main] o.s.a.r.c.CachingConnectionFactory : Created new connection: rabbitConnectionFactory#2a3a299:0/SimpleConnection@66c83fc8. . .
|
||
. . .
|
||
--- [ main] o.s.i.a.i.AmqpInboundChannelAdapter : started inbound.input.anonymous.CbMIwdkJSBO1ZoPDOtHtCg
|
||
. . .
|
||
--- [ main] c.e.l.LoggingConsumerApplication : Started LoggingConsumerApplication in 2.531 seconds (JVM running for 2.897)</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Go to the RabbitMQ management console or any other RabbitMQ client and send a message to <code>input.anonymous.CbMIwdkJSBO1ZoPDOtHtCg</code>.
|
||
The <code>anonymous.CbMIwdkJSBO1ZoPDOtHtCg</code> part represents the group name and is generated, so it is bound to be different in your environment.
|
||
For something more predictable, you can use an explicit group name by setting <code>spring.cloud.stream.bindings.input.group=hello</code> (or whatever name you like).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The contents of the message should be a JSON representation of the <code>Person</code> class, as follows:</p>
|
||
</div>
|
||
<div class="literalblock">
|
||
<div class="content">
|
||
<pre>{"name":"Sam Spade"}</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Then, in your console, you should see:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>Received: Sam Spade</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also build and package your application into a boot jar (by using <code>./mvnw clean install</code>) and run the built JAR by using the <code>java -jar</code> command.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now you have a working (albeit very basic) Spring Cloud Stream application.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_whats_new_in_2_2"><a class="link" href="#_whats_new_in_2_2">What’s New in 2.2?</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream introduces a number of new features, enhancements, and changes in addition to the once already introduced in
|
||
<a href="https://docs.spring.io/spring-cloud-stream/docs/Elmhurst.SR2/reference/htmlsingle/#_what_s_new_in_2_0">version 2.0</a></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following sections outline the most notable ones:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-preface-new-features">New Features and Components</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-preface-notable-enhancements">Notable Enhancements</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-preface-new-features"><a class="link" href="#spring-cloud-stream-preface-new-features">New Features and Components</a></h3>
|
||
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-preface-notable-enhancements"><a class="link" href="#spring-cloud-stream-preface-notable-enhancements">Notable Enhancements</a></h3>
|
||
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-preface-notable-deprecations"><a class="link" href="#spring-cloud-stream-preface-notable-deprecations">Notable Deprecations</a></h3>
|
||
<div class="paragraph">
|
||
<p>As of version 2.2, the following items have been deprecated:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>The spring-cloud-stream-reactive module is deprecated in favor of native support
|
||
via <a href="#spring_cloud_function">Spring Cloud Function</a> programming model.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_notes_on_migrating_from_1_x_to_2_x"><a class="link" href="#_notes_on_migrating_from_1_x_to_2_x">Notes on migrating from 1.x to 2.x?</a></h3>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Due to the improvements in content-type negotiation, the <code>originalContentType</code> header is not used (ignored) since 2.x and only exists for maintaining compatibility with 1.x versions</p>
|
||
</li>
|
||
<li>
|
||
<p>Introduction of <code>@StreamRetryTemplate</code> qualifier. While configuring custom instance of the <code>RetryTemplate</code> and to avoid conflicts you must qualify the instance of such <code>RetryTemplate</code> with this qualifier. See <a href="#_retry_template">Retry Template</a> for more details.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="spring-cloud-stream-overview-introducing"><a class="link" href="#spring-cloud-stream-overview-introducing">Introducing Spring Cloud Stream</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream is a framework for building message-driven microservice applications.
|
||
Spring Cloud Stream builds upon Spring Boot to create standalone, production-grade Spring applications and uses Spring Integration to provide connectivity to message brokers.
|
||
It provides opinionated configuration of middleware from several vendors, introducing the concepts of persistent publish-subscribe semantics, consumer groups, and partitions.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can add the <code>@EnableBinding</code> annotation to your application to get immediate connectivity to a message broker, and you can add <code>@StreamListener</code> to a method to cause it to receive events for stream processing.
|
||
The following example shows a sink application that receives external messages:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableBinding(Sink.class)
|
||
public class VoteRecordingSinkApplication {
|
||
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(VoteRecordingSinkApplication.class, args);
|
||
}
|
||
|
||
@StreamListener(Sink.INPUT)
|
||
public void processVote(Vote vote) {
|
||
votingService.recordVote(vote);
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>@EnableBinding</code> annotation takes one or more interfaces as parameters (in this case, the parameter is a single <code>Sink</code> interface).
|
||
An interface declares input and output channels.
|
||
Spring Cloud Stream provides the <code>Source</code>, <code>Sink</code>, and <code>Processor</code> interfaces. You can also define your own interfaces.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following listing shows the definition of the <code>Sink</code> interface:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface Sink {
|
||
String INPUT = "input";
|
||
|
||
@Input(Sink.INPUT)
|
||
SubscribableChannel input();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>@Input</code> annotation identifies an input channel, through which received messages enter the application.
|
||
The <code>@Output</code> annotation identifies an output channel, through which published messages leave the application.
|
||
The <code>@Input</code> and <code>@Output</code> annotations can take a channel name as a parameter.
|
||
If a name is not provided, the name of the annotated method is used.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream creates an implementation of the interface for you.
|
||
You can use this in the application by autowiring it, as shown in the following example (from a test case):</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringJUnit4ClassRunner.class)
|
||
@SpringApplicationConfiguration(classes = VoteRecordingSinkApplication.class)
|
||
@WebAppConfiguration
|
||
@DirtiesContext
|
||
public class StreamApplicationTests {
|
||
|
||
@Autowired
|
||
private Sink sink;
|
||
|
||
@Test
|
||
public void contextLoads() {
|
||
assertThat(this.sink.input()).isNotNull();
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_main_concepts"><a class="link" href="#_main_concepts">Main Concepts</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides a number of abstractions and primitives that simplify the writing of message-driven microservice applications.
|
||
This section gives an overview of the following:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-overview-application-model">Spring Cloud Stream’s application model</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-overview-binder-abstraction">The Binder Abstraction</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-overview-persistent-publish-subscribe-support">Persistent publish-subscribe support</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#consumer-groups">Consumer group support</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#partitioning">Partitioning support</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="#spring-cloud-stream-overview-binder-api">A pluggable Binder SPI</a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-application-model"><a class="link" href="#spring-cloud-stream-overview-application-model">Application Model</a></h3>
|
||
<div class="paragraph">
|
||
<p>A Spring Cloud Stream application consists of a middleware-neutral core.
|
||
The application communicates with the outside world through input and output channels injected into it by Spring Cloud Stream.
|
||
Channels are connected to external brokers through middleware-specific Binder implementations.</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/SCSt-with-binder.png" alt="SCSt with binder" width="800">
|
||
</div>
|
||
<div class="title">Figure 1. Spring Cloud Stream Application</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_fat_jar"><a class="link" href="#_fat_jar">Fat JAR</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream applications can be run in stand-alone mode from your IDE for testing.
|
||
To run a Spring Cloud Stream application in production, you can create an executable (or “fat”) JAR by using the standard Spring Boot tooling provided for Maven or Gradle. See the <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/howto-build.html#howto-create-an-executable-jar-with-maven">Spring Boot Reference Guide</a> for more details.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-binder-abstraction"><a class="link" href="#spring-cloud-stream-overview-binder-abstraction">The Binder Abstraction</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides Binder implementations for <a href="https://github.com/spring-cloud/spring-cloud-stream-binder-kafka">Kafka</a> and <a href="https://github.com/spring-cloud/spring-cloud-stream-binder-rabbit">Rabbit MQ</a>.
|
||
Spring Cloud Stream also includes a <a href="https://github.com/spring-cloud/spring-cloud-stream/blob/master/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestSupportBinder.java">TestSupportBinder</a>, which leaves a channel unmodified so that tests can interact with channels directly and reliably assert on what is received.
|
||
You can also use the extensible API to write your own Binder.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream uses Spring Boot for configuration, and the Binder abstraction makes it possible for a Spring Cloud Stream application to be flexible in how it connects to middleware.
|
||
For example, deployers can dynamically choose, at runtime, the destinations (such as the Kafka topics or RabbitMQ exchanges) to which channels connect.
|
||
Such configuration can be provided through external configuration properties and in any form supported by Spring Boot (including application arguments, environment variables, and <code>application.yml</code> or <code>application.properties</code> files).
|
||
In the sink example from the <a href="#spring-cloud-stream-overview-introducing">Introducing Spring Cloud Stream</a> section, setting the <code>spring.cloud.stream.bindings.input.destination</code> application property to <code>raw-sensor-data</code> causes it to read from the <code>raw-sensor-data</code> Kafka topic or from a queue bound to the <code>raw-sensor-data</code> RabbitMQ exchange.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream automatically detects and uses a binder found on the classpath.
|
||
You can use different types of middleware with the same code.
|
||
To do so, include a different binder at build time.
|
||
For more complex use cases, you can also package multiple binders with your application and have it choose the binder( and even whether to use different binders for different channels) at runtime.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-persistent-publish-subscribe-support"><a class="link" href="#spring-cloud-stream-overview-persistent-publish-subscribe-support">Persistent Publish-Subscribe Support</a></h3>
|
||
<div class="paragraph">
|
||
<p>Communication between applications follows a publish-subscribe model, where data is broadcast through shared topics.
|
||
This can be seen in the following figure, which shows a typical deployment for a set of interacting Spring Cloud Stream applications.</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/SCSt-sensors.png" alt="SCSt sensors" width="800">
|
||
</div>
|
||
<div class="title">Figure 2. Spring Cloud Stream Publish-Subscribe</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Data reported by sensors to an HTTP endpoint is sent to a common destination named <code>raw-sensor-data</code>.
|
||
From the destination, it is independently processed by a microservice application that computes time-windowed averages and by another microservice application that ingests the raw data into HDFS (Hadoop Distributed File System).
|
||
In order to process the data, both applications declare the topic as their input at runtime.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The publish-subscribe communication model reduces the complexity of both the producer and the consumer and lets new applications be added to the topology without disruption of the existing flow.
|
||
For example, downstream from the average-calculating application, you can add an application that calculates the highest temperature values for display and monitoring.
|
||
You can then add another application that interprets the same flow of averages for fault detection.
|
||
Doing all communication through shared topics rather than point-to-point queues reduces coupling between microservices.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>While the concept of publish-subscribe messaging is not new, Spring Cloud Stream takes the extra step of making it an opinionated choice for its application model.
|
||
By using native middleware support, Spring Cloud Stream also simplifies use of the publish-subscribe model across different platforms.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="consumer-groups"><a class="link" href="#consumer-groups">Consumer Groups</a></h3>
|
||
<div class="paragraph">
|
||
<p>While the publish-subscribe model makes it easy to connect applications through shared topics, the ability to scale up by creating multiple instances of a given application is equally important.
|
||
When doing so, different instances of an application are placed in a competing consumer relationship, where only one of the instances is expected to handle a given message.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream models this behavior through the concept of a consumer group.
|
||
(Spring Cloud Stream consumer groups are similar to and inspired by Kafka consumer groups.)
|
||
Each consumer binding can use the <code>spring.cloud.stream.bindings.<channelName>.group</code> property to specify a group name.
|
||
For the consumers shown in the following figure, this property would be set as <code>spring.cloud.stream.bindings.<channelName>.group=hdfsWrite</code> or <code>spring.cloud.stream.bindings.<channelName>.group=average</code>.</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/SCSt-groups.png" alt="SCSt groups" width="800">
|
||
</div>
|
||
<div class="title">Figure 3. Spring Cloud Stream Consumer Groups</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>All groups that subscribe to a given destination receive a copy of published data, but only one member of each group receives a given message from that destination.
|
||
By default, when a group is not specified, Spring Cloud Stream assigns the application to an anonymous and independent single-member consumer group that is in a publish-subscribe relationship with all other consumer groups.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="consumer-types"><a class="link" href="#consumer-types">Consumer Types</a></h3>
|
||
<div class="paragraph">
|
||
<p>Two types of consumer are supported:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Message-driven (sometimes referred to as Asynchronous)</p>
|
||
</li>
|
||
<li>
|
||
<p>Polled (sometimes referred to as Synchronous)</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Prior to version 2.0, only asynchronous consumers were supported. A message is delivered as soon as it is available and a thread is available to process it.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When you wish to control the rate at which messages are processed, you might want to use a synchronous consumer.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="durability"><a class="link" href="#durability">Durability</a></h4>
|
||
<div class="paragraph">
|
||
<p>Consistent with the opinionated application model of Spring Cloud Stream, consumer group subscriptions are durable.
|
||
That is, a binder implementation ensures that group subscriptions are persistent and that, once at least one subscription for a group has been created, the group receives messages, even if they are sent while all applications in the group are stopped.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
<div class="paragraph">
|
||
<p>Anonymous subscriptions are non-durable by nature.
|
||
For some binder implementations (such as RabbitMQ), it is possible to have non-durable group subscriptions.</p>
|
||
</div>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In general, it is preferable to always specify a consumer group when binding an application to a given destination.
|
||
When scaling up a Spring Cloud Stream application, you must specify a consumer group for each of its input bindings.
|
||
Doing so prevents the application’s instances from receiving duplicate messages (unless that behavior is desired, which is unusual).</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="partitioning"><a class="link" href="#partitioning">Partitioning Support</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides support for partitioning data between multiple instances of a given application.
|
||
In a partitioned scenario, the physical communication medium (such as the broker topic) is viewed as being structured into multiple partitions.
|
||
One or more producer application instances send data to multiple consumer application instances and ensure that data identified by common characteristics are processed by the same consumer instance.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides a common abstraction for implementing partitioned processing use cases in a uniform fashion.
|
||
Partitioning can thus be used whether the broker itself is naturally partitioned (for example, Kafka) or not (for example, RabbitMQ).</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/SCSt-partitioning.png" alt="SCSt partitioning" width="800">
|
||
</div>
|
||
<div class="title">Figure 4. Spring Cloud Stream Partitioning</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Partitioning is a critical concept in stateful processing, where it is critical (for either performance or consistency reasons) to ensure that all related data is processed together.
|
||
For example, in the time-windowed average calculation example, it is important that all measurements from any given sensor are processed by the same application instance.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
To set up a partitioned processing scenario, you must configure both the data-producing and the data-consuming ends.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_programming_model"><a class="link" href="#_programming_model">Programming Model</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>To understand the programming model, you should be familiar with the following core concepts:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><strong>Destination Binders:</strong> Components responsible to provide integration with the external messaging systems.</p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Destination Bindings:</strong> Bridge between the external messaging systems and application provided <em>Producers</em> and <em>Consumers</em> of messages (created by the Destination Binders).</p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Message:</strong> The canonical data structure used by producers and consumers to communicate with Destination Binders (and thus other applications via external messaging systems).</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/SCSt-overview.png" alt="SCSt overview" width="800">
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_destination_binders"><a class="link" href="#_destination_binders">Destination Binders</a></h3>
|
||
<div class="paragraph">
|
||
<p>Destination Binders are extension components of Spring Cloud Stream responsible for providing the necessary configuration and implementation to facilitate
|
||
integration with external messaging systems.
|
||
This integration is responsible for connectivity, delegation, and routing of messages to and from producers and consumers, data type conversion,
|
||
invocation of the user code, and more.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Binders handle a lot of the boiler plate responsibilities that would otherwise fall on your shoulders. However, to accomplish that, the binder still needs
|
||
some help in the form of minimalistic yet required set of instructions from the user, which typically come in the form of some type of configuration.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>While it is out of scope of this section to discuss all of the available binder and binding configuration options (the rest of the manual covers them extensively),
|
||
<em>Destination Binding</em> does require special attention. The next section discusses it in detail.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_destination_bindings"><a class="link" href="#_destination_bindings">Destination Bindings</a></h3>
|
||
<div class="paragraph">
|
||
<p>As stated earlier, <em>Destination Bindings</em> provide a bridge between the external messaging system and application-provided <em>Producers</em> and <em>Consumers</em>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Applying the @EnableBinding annotation to one of the application’s configuration classes defines a destination binding.
|
||
The <code>@EnableBinding</code> annotation itself is meta-annotated with <code>@Configuration</code> and triggers the configuration of the Spring Cloud Stream infrastructure.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows a fully configured and functioning Spring Cloud Stream application that receives the payload of the message from the <code>INPUT</code>
|
||
destination as a <code>String</code> type (see <a href="#content-type-management">Content Type Negotiation</a> section), logs it to the console and sends it to the <code>OUTPUT</code> destination after converting it to upper case.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableBinding(Processor.class)
|
||
public class MyApplication {
|
||
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(MyApplication.class, args);
|
||
}
|
||
|
||
@StreamListener(Processor.INPUT)
|
||
@SendTo(Processor.OUTPUT)
|
||
public String handle(String value) {
|
||
System.out.println("Received: " + value);
|
||
return value.toUpperCase();
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As you can see the <code>@EnableBinding</code> annotation can take one or more interface classes as parameters. The parameters are referred to as <em>bindings</em>,
|
||
and they contain methods representing <em>bindable components</em>.
|
||
These components are typically message channels (see <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-messaging.html">Spring Messaging</a>)
|
||
for channel-based binders (such as Rabbit, Kafka, and others). However other types of bindings can
|
||
provide support for the native features of the corresponding technology. For example Kafka Streams binder (formerly known as KStream) allows native bindings directly to Kafka Streams
|
||
(see <a href="http://cloud.spring.io/spring-cloud-static/spring-cloud-stream-binder-kafka/3.0.0.M3/">Kafka Binder</a> for more details).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream already provides <em>binding</em> interfaces for typical message exchange contracts, which include:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><strong>Sink:</strong> Identifies the contract for the message consumer by providing the destination from which the message is consumed.</p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Source:</strong> Identifies the contract for the message producer by providing the destination to which the produced message is sent.</p>
|
||
</li>
|
||
<li>
|
||
<p><strong>Processor:</strong> Encapsulates both the sink and the source contracts by exposing two destinations that allow consumption and production of messages.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface Sink {
|
||
|
||
String INPUT = "input";
|
||
|
||
@Input(Sink.INPUT)
|
||
SubscribableChannel input();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface Source {
|
||
|
||
String OUTPUT = "output";
|
||
|
||
@Output(Source.OUTPUT)
|
||
MessageChannel output();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface Processor extends Source, Sink {}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>While the preceding example satisfies the majority of cases, you can also define your own contracts by defining your own bindings interfaces and use <code>@Input</code> and <code>@Output</code>
|
||
annotations to identify the actual <em>bindable components</em>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface Barista {
|
||
|
||
@Input
|
||
SubscribableChannel orders();
|
||
|
||
@Output
|
||
MessageChannel hotDrinks();
|
||
|
||
@Output
|
||
MessageChannel coldDrinks();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Using the interface shown in the preceding example as a parameter to <code>@EnableBinding</code> triggers the creation of the three bound channels named <code>orders</code>, <code>hotDrinks</code>, and <code>coldDrinks</code>,
|
||
respectively.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can provide as many binding interfaces as you need, as arguments to the <code>@EnableBinding</code> annotation, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(value = { Orders.class, Payment.class })</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In Spring Cloud Stream, the bindable <code>MessageChannel</code> components are the Spring Messaging <code>MessageChannel</code> (for outbound) and its extension, <code>SubscribableChannel</code>,
|
||
(for inbound).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><strong>Pollable Destination Binding</strong></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>While the previously described bindings support event-based message consumption, sometimes you need more control, such as rate of consumption.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Starting with version 2.0, you can now bind a pollable consumer:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to bind a pollable consumer:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface PolledBarista {
|
||
|
||
@Input
|
||
PollableMessageSource orders();
|
||
. . .
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In this case, an implementation of <code>PollableMessageSource</code> is bound to the <code>orders</code> “channel”. See <a href="#spring-cloud-streams-overview-using-polled-consumers">Using Polled Consumers</a> for more details.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><strong>Customizing Channel Names</strong></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>By using the <code>@Input</code> and <code>@Output</code> annotations, you can specify a customized channel name for the channel, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface Barista {
|
||
@Input("inboundOrders")
|
||
SubscribableChannel orders();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, the created bound channel is named <code>inboundOrders</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Normally, you need not access individual channels or bindings directly (other then configuring them via <code>@EnableBinding</code> annotation). However there may be
|
||
times, such as testing or other corner cases, when you do.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Aside from generating channels for each binding and registering them as Spring beans, for each bound interface, Spring Cloud Stream generates a bean that implements the interface.
|
||
That means you can have access to the interfaces representing the bindings or individual channels by auto-wiring either in your application, as shown in the following two examples:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><em>Autowire Binding interface</em></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Autowired
|
||
private Source source
|
||
|
||
public void sayHello(String name) {
|
||
source.output().send(MessageBuilder.withPayload(name).build());
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><em>Autowire individual channel</em></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Autowired
|
||
private MessageChannel output;
|
||
|
||
public void sayHello(String name) {
|
||
output.send(MessageBuilder.withPayload(name).build());
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also use standard Spring’s <code>@Qualifier</code> annotation for cases when channel names are customized or in multiple-channel scenarios that require specifically named channels.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to use the @Qualifier annotation in this way:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Autowired
|
||
@Qualifier("myChannel")
|
||
private MessageChannel output;</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-producing-consuming-messages"><a class="link" href="#spring-cloud-stream-overview-producing-consuming-messages">Producing and Consuming Messages</a></h3>
|
||
<div class="paragraph">
|
||
<p>You can write a Spring Cloud Stream application by using either Spring Integration annotations or Spring Cloud Stream native annotation.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_spring_integration_support"><a class="link" href="#_spring_integration_support">Spring Integration Support</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream is built on the concepts and patterns defined by <a href="http://www.enterpriseintegrationpatterns.com/">Enterprise Integration Patterns</a> and relies
|
||
in its internal implementation on an already established and popular implementation of Enterprise Integration Patterns within the Spring portfolio of projects:
|
||
<a href="https://projects.spring.io/spring-integration/">Spring Integration</a> framework.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>So its only natural for it to support the foundation, semantics, and configuration options that are already established by Spring Integration</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example, you can attach the output channel of a <code>Source</code> to a <code>MessageSource</code> and use the familiar <code>@InboundChannelAdapter</code> annotation, as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Source.class)
|
||
public class TimerSource {
|
||
|
||
@Bean
|
||
@InboundChannelAdapter(value = Source.OUTPUT, poller = @Poller(fixedDelay = "10", maxMessagesPerPoll = "1"))
|
||
public MessageSource<String> timerMessageSource() {
|
||
return () -> new GenericMessage<>("Hello Spring Cloud Stream");
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Similarly, you can use @Transformer or @ServiceActivator while providing an implementation of a message handler method for a <em>Processor</em> binding contract, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Processor.class)
|
||
public class TransformProcessor {
|
||
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
|
||
public Object transform(String message) {
|
||
return message.toUpperCase();
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
While this may be skipping ahead a bit, it is important to understand that, when you consume from the same binding using <code>@StreamListener</code> annotation, a pub-sub model is used.
|
||
Each method annotated with <code>@StreamListener</code> receives its own copy of a message, and each one has its own consumer group.
|
||
However, if you consume from the same binding by using one of the Spring Integration annotation (such as <code>@Aggregator</code>, <code>@Transformer</code>, or <code>@ServiceActivator</code>), those consume in a competing model.
|
||
No individual consumer group is created for each subscription.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_using_streamlistener_annotation"><a class="link" href="#_using_streamlistener_annotation">Using @StreamListener Annotation</a></h4>
|
||
<div class="paragraph">
|
||
<p>Complementary to its Spring Integration support, Spring Cloud Stream provides its own <code>@StreamListener</code> annotation, modeled after other Spring Messaging annotations
|
||
(<code>@MessageMapping</code>, <code>@JmsListener</code>, <code>@RabbitListener</code>, and others) and provides conviniences, such as content-based routing and others.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Sink.class)
|
||
public class VoteHandler {
|
||
|
||
@Autowired
|
||
VotingService votingService;
|
||
|
||
@StreamListener(Sink.INPUT)
|
||
public void handle(Vote vote) {
|
||
votingService.record(vote);
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As with other Spring Messaging methods, method arguments can be annotated with <code>@Payload</code>, <code>@Headers</code>, and <code>@Header</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For methods that return data, you must use the <code>@SendTo</code> annotation to specify the output binding destination for data returned by the method, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Processor.class)
|
||
public class TransformProcessor {
|
||
|
||
@Autowired
|
||
VotingService votingService;
|
||
|
||
@StreamListener(Processor.INPUT)
|
||
@SendTo(Processor.OUTPUT)
|
||
public VoteResult handle(Vote vote) {
|
||
return votingService.record(vote);
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_using_streamlistener_for_content_based_routing"><a class="link" href="#_using_streamlistener_for_content_based_routing">Using @StreamListener for Content-based routing</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream supports dispatching messages to multiple handler methods annotated with <code>@StreamListener</code> based on conditions.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In order to be eligible to support conditional dispatching, a method must satisfy the follow conditions:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>It must not return a value.</p>
|
||
</li>
|
||
<li>
|
||
<p>It must be an individual message handling method (reactive API methods are not supported).</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The condition is specified by a SpEL expression in the <code>condition</code> argument of the annotation and is evaluated for each message.
|
||
All the handlers that match the condition are invoked in the same thread, and no assumption must be made about the order in which the invocations take place.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the following example of a <code>@StreamListener</code> with dispatching conditions, all the messages bearing a header <code>type</code> with the value <code>bogey</code> are dispatched to the
|
||
<code>receiveBogey</code> method, and all the messages bearing a header <code>type</code> with the value <code>bacall</code> are dispatched to the <code>receiveBacall</code> method.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Sink.class)
|
||
@EnableAutoConfiguration
|
||
public static class TestPojoWithAnnotatedArguments {
|
||
|
||
@StreamListener(target = Sink.INPUT, condition = "headers['type']=='bogey'")
|
||
public void receiveBogey(@Payload BogeyPojo bogeyPojo) {
|
||
// handle the message
|
||
}
|
||
|
||
@StreamListener(target = Sink.INPUT, condition = "headers['type']=='bacall'")
|
||
public void receiveBacall(@Payload BacallPojo bacallPojo) {
|
||
// handle the message
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><strong>Content Type Negotiation in the Context of <code>condition</code></strong></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>It is important to understand some of the mechanics behind content-based routing using the <code>condition</code> argument of <code>@StreamListener</code>, especially in the context of the type of the message as a whole.
|
||
It may also help if you familiarize yourself with the <a href="#content-type-management">Content Type Negotiation</a> before you proceed.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following scenario:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Sink.class)
|
||
@EnableAutoConfiguration
|
||
public static class CatsAndDogs {
|
||
|
||
@StreamListener(target = Sink.INPUT, condition = "payload.class.simpleName=='Dog'")
|
||
public void bark(Dog dog) {
|
||
// handle the message
|
||
}
|
||
|
||
@StreamListener(target = Sink.INPUT, condition = "payload.class.simpleName=='Cat'")
|
||
public void purr(Cat cat) {
|
||
// handle the message
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding code is perfectly valid. It compiles and deploys without any issues, yet it never produces the result you expect.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>That is because you are testing something that does not yet exist in a state you expect. That is because the payload of the message is not yet converted from the
|
||
wire format (<code>byte[]</code>) to the desired type.
|
||
In other words, it has not yet gone through the type conversion process described in the <a href="#content-type-management">Content Type Negotiation</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>So, unless you use a SPeL expression that evaluates raw data (for example, the value of the first byte in the byte array), use message header-based expressions
|
||
(such as <code>condition = "headers['type']=='dog'"</code>).</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
At the moment, dispatching through <code>@StreamListener</code> conditions is supported only for channel-based binders (not for reactive programming)
|
||
support.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring_cloud_function"><a class="link" href="#spring_cloud_function">Spring Cloud Function support</a></h4>
|
||
<div class="sect4">
|
||
<h5 id="_overview"><a class="link" href="#_overview">Overview</a></h5>
|
||
<div class="paragraph">
|
||
<p>Since Spring Cloud Stream v2.1, another alternative for defining <em>stream handlers</em> and <em>sources</em> is to use build-in
|
||
support for <a href="https://cloud.spring.io/spring-cloud-function/">Spring Cloud Function</a> where they can be expressed as beans of
|
||
type <code>java.util.function.[Supplier/Function/Consumer]</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To specify which functional bean to bind to the external destination(s) exposed by the bindings, you must provide <code>spring.cloud.stream.function.definition</code> or native to spring-cloud-function <code>spring.cloud.function.definition</code> property.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Here is the example of the Processor application exposing message handler as <code>java.util.function.Function</code></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableBinding(Processor.class)
|
||
public class MyFunctionBootApp {
|
||
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(MyFunctionBootApp.class, "--spring.cloud.function.definition=toUpperCase");
|
||
}
|
||
|
||
@Bean
|
||
public Function<String, String> toUpperCase() {
|
||
return s -> s.toUpperCase();
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the above you we simply define a bean of type <code>java.util.function.Function</code> called <em>toUpperCase</em> and identify it as a bean to be used as message handler
|
||
whose 'input' and 'output' must be bound to the external destinations exposed by the Processor binding.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Below are the examples of simple functional applications to support Source, Processor and Sink.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Here is the example of a Source application defined as <code>java.util.function.Supplier</code></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableBinding(Source.class)
|
||
public static class SourceFromSupplier {
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(SourceFromSupplier.class, "--spring.cloud.stream.function.definition=date");
|
||
}
|
||
@Bean
|
||
public Supplier<Date> date() {
|
||
return () -> new Date(12345L);
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Here is the example of a Processor application defined as <code>java.util.function.Function</code></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableBinding(Processor.class)
|
||
public static class ProcessorFromFunction {
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(ProcessorFromFunction.class, "--spring.cloud.stream.function.definition=toUpperCase");
|
||
}
|
||
@Bean
|
||
public Function<String, String> toUpperCase() {
|
||
return s -> s.toUpperCase();
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Here is the example of a Sink application defined as <code>java.util.function.Consumer</code></p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableAutoConfiguration
|
||
@EnableBinding(Sink.class)
|
||
public static class SinkFromConsumer {
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(SinkFromConsumer.class, "--spring.cloud.stream.function.definition=sink");
|
||
}
|
||
@Bean
|
||
public Consumer<String> sink() {
|
||
return System.out::println;
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="_reactive_functions_support"><a class="link" href="#_reactive_functions_support">Reactive Functions support</a></h5>
|
||
<div class="paragraph">
|
||
<p>Since <em>Spring Cloud Function</em> is build on top of <a href="https://projectreactor.io/">Project Reactor</a> there isn’t much you need to do
|
||
to benefit from reactive programming model while implementing <code>Supplier</code>, <code>Function</code> or <code>Consumer</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableAutoConfiguration
|
||
@EnableBinding(Processor.class)
|
||
public static class SinkFromConsumer {
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(SinkFromConsumer.class, "--spring.cloud.stream.function.definition=reactiveUpperCase");
|
||
}
|
||
@Bean
|
||
public Function<Flux<String>, Flux<String>> reactiveUpperCase() {
|
||
return flux -> flux.map(val -> val.toUpperCase());
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="_functional_composition"><a class="link" href="#_functional_composition">Functional Composition</a></h5>
|
||
<div class="paragraph">
|
||
<p>Using this programming model you can also benefit from functional composition where you can dynamically compose complex handlers from a set of simple functions.
|
||
As an example let’s add the following function bean to the application defined above</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public Function<String, String> wrapInQuotes() {
|
||
return s -> "\"" + s + "\"";
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>and modify the <code>spring.cloud.stream.function.definition</code> property to reflect your intention to compose a new function from both ‘toUpperCase’ and ‘wrapInQuotes’.
|
||
To do that Spring Cloud Function allows you to use <code>|</code> (pipe) symbol. So to finish our example our property will now look like this:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">--spring.cloud.stream.function.definition=toUpperCase|wrapInQuotes</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
One of the great benefits of functional composition support provided by <em>Spring Cloud Function</em> is
|
||
the fact that you can compose <em>reactive</em> and <em>imperative</em> functions.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example, the above composition could be defined as such (if both functions present):</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">--spring.cloud.stream.function.definition=reactiveUpperCase|wrapInQuotes</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="_batch_consumers"><a class="link" href="#_batch_consumers">Batch Consumers</a></h5>
|
||
<div class="paragraph">
|
||
<p>When using a <code>MessageChannelBinder</code> that supports batch listeners, and the feature is enabled for the consumer binding, you can set <code>spring.cloud.stream.function.definition</code> to <code>true</code> to enable the entire batch of messages to be passed to the function in a <code>List</code>.</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public Function<List<Person>, Person> findFirstPerson() {
|
||
return persons -> persons.get(0);
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-streams-overview-using-polled-consumers"><a class="link" href="#spring-cloud-streams-overview-using-polled-consumers">Using Polled Consumers</a></h4>
|
||
<div class="sect4">
|
||
<h5 id="_overview_2"><a class="link" href="#_overview_2">Overview</a></h5>
|
||
<div class="paragraph">
|
||
<p>When using polled consumers, you poll the <code>PollableMessageSource</code> on demand.
|
||
Consider the following example of a polled consumer:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface PolledConsumer {
|
||
|
||
@Input
|
||
PollableMessageSource destIn();
|
||
|
||
@Output
|
||
MessageChannel destOut();
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Given the polled consumer in the preceding example, you might use it as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public ApplicationRunner poller(PollableMessageSource destIn, MessageChannel destOut) {
|
||
return args -> {
|
||
while (someCondition()) {
|
||
try {
|
||
if (!destIn.poll(m -> {
|
||
String newPayload = ((String) m.getPayload()).toUpperCase();
|
||
destOut.send(new GenericMessage<>(newPayload));
|
||
})) {
|
||
Thread.sleep(1000);
|
||
}
|
||
}
|
||
catch (Exception e) {
|
||
// handle failure
|
||
}
|
||
}
|
||
};
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A less manual and more Spring-like alternative would be to configure a scheduled task bean. For example,</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Scheduled(fixedDelay = 5_000)
|
||
public void poll() {
|
||
System.out.println("Polling...");
|
||
this.source.poll(m -> {
|
||
System.out.println(m.getPayload());
|
||
|
||
}, new ParameterizedTypeReference<Foo>() { });
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>PollableMessageSource.poll()</code> method takes a <code>MessageHandler</code> argument (often a lambda expression, as shown here).
|
||
It returns <code>true</code> if the message was received and successfully processed.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As with message-driven consumers, if the <code>MessageHandler</code> throws an exception, messages are published to error channels,
|
||
as discussed in <code><a href="#spring-cloud-stream-overview-error-handling">Error Handling</a></code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Normally, the <code>poll()</code> method acknowledges the message when the <code>MessageHandler</code> exits.
|
||
If the method exits abnormally, the message is rejected (not re-queued), but see <a href="#polled-errors">Handling Errors</a>.
|
||
You can override that behavior by taking responsibility for the acknowledgment, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public ApplicationRunner poller(PollableMessageSource dest1In, MessageChannel dest2Out) {
|
||
return args -> {
|
||
while (someCondition()) {
|
||
if (!dest1In.poll(m -> {
|
||
StaticMessageHeaderAccessor.getAcknowledgmentCallback(m).noAutoAck();
|
||
// e.g. hand off to another thread which can perform the ack
|
||
// or acknowledge(Status.REQUEUE)
|
||
|
||
})) {
|
||
Thread.sleep(1000);
|
||
}
|
||
}
|
||
};
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock important">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-important" title="Important"></i>
|
||
</td>
|
||
<td class="content">
|
||
You must <code>ack</code> (or <code>nack</code>) the message at some point, to avoid resource leaks.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="admonitionblock important">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-important" title="Important"></i>
|
||
</td>
|
||
<td class="content">
|
||
Some messaging systems (such as Apache Kafka) maintain a simple offset in a log. If a delivery fails and is re-queued with <code>StaticMessageHeaderAccessor.getAcknowledgmentCallback(m).acknowledge(Status.REQUEUE);</code>, any later successfully ack’d messages are redelivered.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>There is also an overloaded <code>poll</code> method, for which the definition is as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">poll(MessageHandler handler, ParameterizedTypeReference<?> type)</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>type</code> is a conversion hint that allows the incoming message payload to be converted, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">boolean result = pollableSource.poll(received -> {
|
||
Map<String, Foo> payload = (Map<String, Foo>) received.getPayload();
|
||
...
|
||
|
||
}, new ParameterizedTypeReference<Map<String, Foo>>() {});</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="polled-errors"><a class="link" href="#polled-errors">Handling Errors</a></h5>
|
||
<div class="paragraph">
|
||
<p>By default, an error channel is configured for the pollable source; if the callback throws an exception, an <code>ErrorMessage</code> is sent to the error channel (<code><destination>.<group>.errors</code>); this error channel is also bridged to the global Spring Integration <code>errorChannel</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can subscribe to either error channel with a <code>@ServiceActivator</code> to handle errors; without a subscription, the error will simply be logged and the message will be acknowledged as successful.
|
||
If the error channel service activator throws an exception, the message will be rejected (by default) and won’t be redelivered.
|
||
If the service activator throws a <code>RequeueCurrentMessageException</code>, the message will be requeued at the broker and will be again retrieved on a subsequent poll.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If the listener throws a <code>RequeueCurrentMessageException</code> directly, the message will be requeued, as discussed above, and will not be sent to the error channels.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-error-handling"><a class="link" href="#spring-cloud-stream-overview-error-handling">Error Handling</a></h3>
|
||
<div class="paragraph">
|
||
<p>Errors happen, and Spring Cloud Stream provides several flexible mechanisms to handle them.
|
||
The error handling comes in two flavors:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><strong>application:</strong> The error handling is done within the application (custom error handler).</p>
|
||
</li>
|
||
<li>
|
||
<p><strong>system:</strong> The error handling is delegated to the binder (re-queue, DL, and others). Note that the techniques are dependent on binder implementation and the
|
||
capability of the underlying messaging middleware.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream uses the <a href="https://github.com/spring-projects/spring-retry">Spring Retry</a> library to facilitate successful message processing. See <a href="#_retry_template">Retry Template</a> for more details.
|
||
However, when all fails, the exceptions thrown by the message handlers are propagated back to the binder. At that point, binder invokes custom error handler or communicates
|
||
the error back to the messaging system (re-queue, DLQ, and others).</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_application_error_handling"><a class="link" href="#_application_error_handling">Application Error Handling</a></h4>
|
||
<div class="paragraph">
|
||
<p>There are two types of application-level error handling. Errors can be handled at each binding subscription or a global handler can handle all the binding subscription errors. Let’s review the details.</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/custom_vs_global_error_channels.png" alt="custom vs global error channels" width="800">
|
||
</div>
|
||
<div class="title">Figure 5. A Spring Cloud Stream Sink Application with Custom and Global Error Handlers</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For each input binding, Spring Cloud Stream creates a dedicated error channel with the following semantics <code><destinationName>.errors</code>.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The <code><destinationName></code> consists of the name of the binding (such as <code>input</code>) and the name of the group (such as <code>myGroup</code>).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">spring.cloud.stream.bindings.input.group=myGroup</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@StreamListener(Sink.INPUT) // destination name 'input.myGroup'
|
||
public void handle(Person value) {
|
||
throw new RuntimeException("BOOM!");
|
||
}
|
||
|
||
@ServiceActivator(inputChannel = Processor.INPUT + ".myGroup.errors") //channel name 'input.myGroup.errors'
|
||
public void error(Message<?> message) {
|
||
System.out.println("Handling ERROR: " + message);
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example the destination name is <code>input.myGroup</code> and the dedicated error channel name is <code>input.myGroup.errors</code>.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The use of @StreamListener annotation is intended specifically to define bindings that bridge internal channels and external destinations. Given that the destination
|
||
specific error channel does NOT have an associated external destination, such channel is a prerogative of Spring Integration (SI). This means that the handler
|
||
for such destination must be defined using one of the SI handler annotations (i.e., @ServiceActivator, @Transformer etc.).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
If <code>group</code> is not specified anonymous group is used (something like <code>input.anonymous.2K37rb06Q6m2r51-SPIDDQ</code>), which is not suitable for error
|
||
handling scenarious, since you don’t know what it’s going to be until the destination is created.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Also, in the event you are binding to the existing destination such as:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">spring.cloud.stream.bindings.input.destination=myFooDestination
|
||
spring.cloud.stream.bindings.input.group=myGroup</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>the full destination name is <code>myFooDestination.myGroup</code> and then the dedicated error channel name is <code>myFooDestination.myGroup.errors</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Back to the example…​</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>handle(..)</code> method, which subscribes to the channel named <code>input</code>, throws an exception. Given there is also a subscriber to the error channel <code>input.myGroup.errors</code>
|
||
all error messages are handled by this subscriber.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you have multiple bindings, you may want to have a single error handler. Spring Cloud Stream automatically provides support for
|
||
a <em>global error channel</em> by bridging each individual error channel to the channel named <code>errorChannel</code>, allowing a single subscriber to handle all errors,
|
||
as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@StreamListener("errorChannel")
|
||
public void error(Message<?> message) {
|
||
System.out.println("Handling ERROR: " + message);
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This may be a convenient option if error handling logic is the same regardless of which handler produced the error.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_system_error_handling"><a class="link" href="#_system_error_handling">System Error Handling</a></h4>
|
||
<div class="paragraph">
|
||
<p>System-level error handling implies that the errors are communicated back to the messaging system and, given that not every messaging system
|
||
is the same, the capabilities may differ from binder to binder.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>That said, in this section we explain the general idea behind system level error handling and use Rabbit binder as an example. NOTE: Kafka binder provides similar
|
||
support, although some configuration properties do differ. Also, for more details and configuration options, see the individual binder’s documentation.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If no internal error handlers are configured, the errors propagate to the binders, and the binders subsequently propagate those errors back to the messaging system.
|
||
Depending on the capabilities of the messaging system such a system may <em>drop</em> the message, <em>re-queue</em> the message for re-processing or <em>send the failed message to DLQ</em>.
|
||
Both Rabbit and Kafka support these concepts. However, other binders may not, so refer to your individual binder’s documentation for details on supported system-level
|
||
error-handling options.</p>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="_drop_failed_messages"><a class="link" href="#_drop_failed_messages">Drop Failed Messages</a></h5>
|
||
<div class="paragraph">
|
||
<p>By default, if no additional system-level configuration is provided, the messaging system drops the failed message.
|
||
While acceptable in some cases, for most cases, it is not, and we need some recovery mechanism to avoid message loss.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="_dlq_dead_letter_queue"><a class="link" href="#_dlq_dead_letter_queue">DLQ - Dead Letter Queue</a></h5>
|
||
<div class="paragraph">
|
||
<p>DLQ allows failed messages to be sent to a special destination: - <em>Dead Letter Queue</em>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When configured, failed messages are sent to this destination for subsequent re-processing or auditing and reconciliation.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example, continuing on the previous example and to set up the DLQ with Rabbit binder, you need to set the following property:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">spring.cloud.stream.rabbit.bindings.input.consumer.auto-bind-dlq=true</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Keep in mind that, in the above property, <code>input</code> corresponds to the name of the input destination binding.
|
||
The <code>consumer</code> indicates that it is a consumer property and <code>auto-bind-dlq</code> instructs the binder to configure DLQ for <code>input</code>
|
||
destination, which results in an additional Rabbit queue named <code>input.myGroup.dlq</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Once configured, all failed messages are routed to this queue with an error message similar to the following:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">delivery_mode: 1
|
||
headers:
|
||
x-death:
|
||
count: 1
|
||
reason: rejected
|
||
queue: input.hello
|
||
time: 1522328151
|
||
exchange:
|
||
routing-keys: input.myGroup
|
||
Payload {"name”:"Bob"}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As you can see from the above, your original message is preserved for further actions.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>However, one thing you may have noticed is that there is limited information on the original issue with the message processing. For example, you do not see a stack
|
||
trace corresponding to the original error.
|
||
To get more relevant information about the original error, you must set an additional property:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">spring.cloud.stream.rabbit.bindings.input.consumer.republish-to-dlq=true</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Doing so forces the internal error handler to intercept the error message and add additional information to it before publishing it to DLQ.
|
||
Once configured, you can see that the error message contains more information relevant to the original error, as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">delivery_mode: 2
|
||
headers:
|
||
x-original-exchange:
|
||
x-exception-message: has an error
|
||
x-original-routingKey: input.myGroup
|
||
x-exception-stacktrace: org.springframework.messaging.MessageHandlingException: nested exception is
|
||
org.springframework.messaging.MessagingException: has an error, failedMessage=GenericMessage [payload=byte[15],
|
||
headers={amqp_receivedDeliveryMode=NON_PERSISTENT, amqp_receivedRoutingKey=input.hello, amqp_deliveryTag=1,
|
||
deliveryAttempt=3, amqp_consumerQueue=input.hello, amqp_redelivered=false, id=a15231e6-3f80-677b-5ad7-d4b1e61e486e,
|
||
amqp_consumerTag=amq.ctag-skBFapilvtZhDsn0k3ZmQg, contentType=application/json, timestamp=1522327846136}]
|
||
at org.spring...integ...han...MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:107)
|
||
at. . . . .
|
||
Payload {"name”:"Bob"}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This effectively combines application-level and system-level error handling to further assist with downstream troubleshooting mechanics.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="_re_queue_failed_messages"><a class="link" href="#_re_queue_failed_messages">Re-queue Failed Messages</a></h5>
|
||
<div class="paragraph">
|
||
<p>As mentioned earlier, the currently supported binders (Rabbit and Kafka) rely on <code>RetryTemplate</code> to facilitate successful message processing. See <a href="#_retry_template">Retry Template</a> for details.
|
||
However, for cases when <code>max-attempts</code> property is set to 1, internal reprocessing of the message is disabled. At this point, you can facilitate message re-processing (re-tries)
|
||
by instructing the messaging system to re-queue the failed message. Once re-queued, the failed message is sent back to the original handler, essentially creating a retry loop.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This option may be feasible for cases where the nature of the error is related to some sporadic yet short-term unavailability of some resource.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To accomplish that, you must set the following properties:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">spring.cloud.stream.bindings.input.consumer.max-attempts=1
|
||
spring.cloud.stream.rabbit.bindings.input.consumer.requeue-rejected=true</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, the <code>max-attempts</code> set to 1 essentially disabling internal re-tries and <code>requeue-rejected</code> (short for <em>requeue rejected messages</em>) is set to <code>true</code>.
|
||
Once set, the failed message is resubmitted to the same handler and loops continuously or until the handler throws <code>AmqpRejectAndDontRequeueException</code>
|
||
essentially allowing you to build your own re-try logic within the handler itself.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_retry_template"><a class="link" href="#_retry_template">Retry Template</a></h4>
|
||
<div class="paragraph">
|
||
<p>The <code>RetryTemplate</code> is part of the <a href="https://github.com/spring-projects/spring-retry">Spring Retry</a> library.
|
||
While it is out of scope of this document to cover all of the capabilities of the <code>RetryTemplate</code>, we will mention the following consumer properties that are specifically related to
|
||
the <code>RetryTemplate</code>:</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">maxAttempts</dt>
|
||
<dd>
|
||
<p>The number of attempts to process the message.</p>
|
||
<div class="paragraph">
|
||
<p>Default: 3.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">backOffInitialInterval</dt>
|
||
<dd>
|
||
<p>The backoff initial interval on retry.</p>
|
||
<div class="paragraph">
|
||
<p>Default 1000 milliseconds.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">backOffMaxInterval</dt>
|
||
<dd>
|
||
<p>The maximum backoff interval.</p>
|
||
<div class="paragraph">
|
||
<p>Default 10000 milliseconds.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">backOffMultiplier</dt>
|
||
<dd>
|
||
<p>The backoff multiplier.</p>
|
||
<div class="paragraph">
|
||
<p>Default 2.0.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">defaultRetryable</dt>
|
||
<dd>
|
||
<p>Whether exceptions thrown by the listener that are not listed in the <code>retryableExceptions</code> are retryable.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>true</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">retryableExceptions</dt>
|
||
<dd>
|
||
<p>A map of Throwable class names in the key and a boolean in the value.
|
||
Specify those exceptions (and subclasses) that will or won’t be retried.
|
||
Also see <code>defaultRetriable</code>.
|
||
Example: <code>spring.cloud.stream.bindings.input.consumer.retryable-exceptions.java.lang.IllegalStateException=false</code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: empty.</p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>While the preceding settings are sufficient for majority of the customization requirements, they may not satisfy certain complex requirements at, which
|
||
point you may want to provide your own instance of the <code>RetryTemplate</code>. To do so configure it as a bean in your application configuration. The application provided
|
||
instance will override the one provided by the framework. Also, to avoid conflicts you must qualify the instance of the <code>RetryTemplate</code> you want to be used by the binder
|
||
as <code>@StreamRetryTemplate</code>. For example,</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@StreamRetryTemplate
|
||
public RetryTemplate myRetryTemplate() {
|
||
return new RetryTemplate();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As you can see from the above example you don’t need to annotate it with <code>@Bean</code> since <code>@StreamRetryTemplate</code> is a qualified <code>@Bean</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you need to be more precise with your <code>RetryTemplate</code>, you can specify the bean by name in your <code>ConsumerProperties</code> to associate
|
||
the specific retry bean per binding.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>spring.cloud.stream.bindings.<foo>.consumer.retry-template-name=<your-retry-template-bean-name></code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="spring-cloud-stream-overview-binders"><a class="link" href="#spring-cloud-stream-overview-binders">Binders</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides a Binder abstraction for use in connecting to physical destinations at the external middleware.
|
||
This section provides information about the main concepts behind the Binder SPI, its main components, and implementation-specific details.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_producers_and_consumers"><a class="link" href="#_producers_and_consumers">Producers and Consumers</a></h3>
|
||
<div class="paragraph">
|
||
<p>The following image shows the general relationship of producers and consumers:</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/producers-consumers.png" alt="producers consumers" width="800">
|
||
</div>
|
||
<div class="title">Figure 6. Producers and Consumers</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A producer is any component that sends messages to a channel.
|
||
The channel can be bound to an external message broker with a <code>Binder</code> implementation for that broker.
|
||
When invoking the <code>bindProducer()</code> method, the first parameter is the name of the destination within the broker, the second parameter is the local channel instance to which the producer sends messages, and the third parameter contains properties (such as a partition key expression) to be used within the adapter that is created for that channel.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A consumer is any component that receives messages from a channel.
|
||
As with a producer, the consumer’s channel can be bound to an external message broker.
|
||
When invoking the <code>bindConsumer()</code> method, the first parameter is the destination name, and a second parameter provides the name of a logical group of consumers.
|
||
Each group that is represented by consumer bindings for a given destination receives a copy of each message that a producer sends to that destination (that is, it follows normal publish-subscribe semantics).
|
||
If there are multiple consumer instances bound with the same group name, then messages are load-balanced across those consumer instances so that each message sent by a producer is consumed by only a single consumer instance within each group (that is, it follows normal queueing semantics).</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-binder-api"><a class="link" href="#spring-cloud-stream-overview-binder-api">Binder SPI</a></h3>
|
||
<div class="paragraph">
|
||
<p>The Binder SPI consists of a number of interfaces, out-of-the box utility classes, and discovery strategies that provide a pluggable mechanism for connecting to external middleware.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The key point of the SPI is the <code>Binder</code> interface, which is a strategy for connecting inputs and outputs to external middleware. The following listing shows the definnition of the <code>Binder</code> interface:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface Binder<T, C extends ConsumerProperties, P extends ProducerProperties> {
|
||
Binding<T> bindConsumer(String name, String group, T inboundBindTarget, C consumerProperties);
|
||
|
||
Binding<T> bindProducer(String name, T outboundBindTarget, P producerProperties);
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The interface is parameterized, offering a number of extension points:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Input and output bind targets. As of version 1.0, only <code>MessageChannel</code> is supported, but this is intended to be used as an extension point in the future.</p>
|
||
</li>
|
||
<li>
|
||
<p>Extended consumer and producer properties, allowing specific Binder implementations to add supplemental properties that can be supported in a type-safe manner.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A typical binder implementation consists of the following:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>A class that implements the <code>Binder</code> interface;</p>
|
||
</li>
|
||
<li>
|
||
<p>A Spring <code>@Configuration</code> class that creates a bean of type <code>Binder</code> along with the middleware connection infrastructure.</p>
|
||
</li>
|
||
<li>
|
||
<p>A <code>META-INF/spring.binders</code> file found on the classpath containing one or more binder definitions, as shown in the following example:</p>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>kafka:\
|
||
org.springframework.cloud.stream.binder.kafka.config.KafkaBinderConfiguration</code></pre>
|
||
</div>
|
||
</div>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_binder_detection"><a class="link" href="#_binder_detection">Binder Detection</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream relies on implementations of the Binder SPI to perform the task of connecting channels to message brokers.
|
||
Each Binder implementation typically connects to one type of messaging system.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_classpath_detection"><a class="link" href="#_classpath_detection">Classpath Detection</a></h4>
|
||
<div class="paragraph">
|
||
<p>By default, Spring Cloud Stream relies on Spring Boot’s auto-configuration to configure the binding process.
|
||
If a single Binder implementation is found on the classpath, Spring Cloud Stream automatically uses it.
|
||
For example, a Spring Cloud Stream project that aims to bind only to RabbitMQ can add the following dependency:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For the specific Maven coordinates of other binder dependencies, see the documentation of that binder implementation.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="multiple-binders"><a class="link" href="#multiple-binders">Multiple Binders on the Classpath</a></h3>
|
||
<div class="paragraph">
|
||
<p>When multiple binders are present on the classpath, the application must indicate which binder is to be used for each channel binding.
|
||
Each binder configuration contains a <code>META-INF/spring.binders</code> file, which is a simple properties file, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>rabbit:\
|
||
org.springframework.cloud.stream.binder.rabbit.config.RabbitServiceAutoConfiguration</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Similar files exist for the other provided binder implementations (such as Kafka), and custom binder implementations are expected to provide them as well.
|
||
The key represents an identifying name for the binder implementation, whereas the value is a comma-separated list of configuration classes that each contain one and only one bean definition of type <code>org.springframework.cloud.stream.binder.Binder</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Binder selection can either be performed globally, using the <code>spring.cloud.stream.defaultBinder</code> property (for example, <code>spring.cloud.stream.defaultBinder=rabbit</code>) or individually, by configuring the binder on each channel binding.
|
||
For instance, a processor application (that has channels named <code>input</code> and <code>output</code> for read and write respectively) that reads from Kafka and writes to RabbitMQ can specify the following configuration:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>spring.cloud.stream.bindings.input.binder=kafka
|
||
spring.cloud.stream.bindings.output.binder=rabbit</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="multiple-systems"><a class="link" href="#multiple-systems">Connecting to Multiple Systems</a></h3>
|
||
<div class="paragraph">
|
||
<p>By default, binders share the application’s Spring Boot auto-configuration, so that one instance of each binder found on the classpath is created.
|
||
If your application should connect to more than one broker of the same type, you can specify multiple binder configurations, each with different environment settings.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Turning on explicit binder configuration disables the default binder configuration process altogether.
|
||
If you do so, all binders in use must be included in the configuration.
|
||
Frameworks that intend to use Spring Cloud Stream transparently may create binder configurations that can be referenced by name, but they do not affect the default binder configuration.
|
||
In order to do so, a binder configuration may have its <code>defaultCandidate</code> flag set to false (for example, <code>spring.cloud.stream.binders.<configurationName>.defaultCandidate=false</code>).
|
||
This denotes a configuration that exists independently of the default binder configuration process.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows a typical configuration for a processor application that connects to two RabbitMQ broker instances:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yml hljs" data-lang="yml">spring:
|
||
cloud:
|
||
stream:
|
||
bindings:
|
||
input:
|
||
destination: thing1
|
||
binder: rabbit1
|
||
output:
|
||
destination: thing2
|
||
binder: rabbit2
|
||
binders:
|
||
rabbit1:
|
||
type: rabbit
|
||
environment:
|
||
spring:
|
||
rabbitmq:
|
||
host: <host1>
|
||
rabbit2:
|
||
type: rabbit
|
||
environment:
|
||
spring:
|
||
rabbitmq:
|
||
host: <host2></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The <code>environment</code> property of the particular binder can also be used for any Spring Boot property,
|
||
including this <code>spring.main.sources</code> which can be useful for adding additional configurations for the
|
||
particular binders, e.g. overriding auto-configured beans.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example;</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">environment:
|
||
spring:
|
||
main:
|
||
sources: com.acme.config.MyCustomBinderConfiguration</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To activate a specific profile for the particular binder environment, you should use a <code>spring.profiles.active</code> property:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-yaml hljs" data-lang="yaml">environment:
|
||
spring:
|
||
profiles:
|
||
active: myBinderProfile</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="binding_visualization_control"><a class="link" href="#binding_visualization_control">Binding visualization and control</a></h3>
|
||
<div class="paragraph">
|
||
<p>Since version 2.0, Spring Cloud Stream supports visualization and control of the Bindings through Actuator endpoints.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Starting with version 2.0 actuator and web are optional, you must first add one of the web dependencies as well as add the actuator dependency manually.
|
||
The following example shows how to add the dependency for the Web framework:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-starter-web</artifactId>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to add the dependency for the WebFlux framework:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can add the Actuator dependency as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
To run Spring Cloud Stream 2.0 apps in Cloud Foundry, you must add <code>spring-boot-starter-web</code> and <code>spring-boot-starter-actuator</code> to the classpath. Otherwise, the
|
||
application will not start due to health check failures.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You must also enable the <code>bindings</code> actuator endpoints by setting the following property: <code>--management.endpoints.web.exposure.include=bindings</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Once those prerequisites are satisfied. you should see the following in the logs when application start:</p>
|
||
</div>
|
||
<div class="literalblock">
|
||
<div class="content">
|
||
<pre>: Mapped "{[/actuator/bindings/{name}],methods=[POST]. . .
|
||
: Mapped "{[/actuator/bindings],methods=[GET]. . .
|
||
: Mapped "{[/actuator/bindings/{name}],methods=[GET]. . .</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To visualize the current bindings, access the following URL:
|
||
<code><a href="http://<host>:<port>/actuator/bindings" class="bare">http://<host>:<port>/actuator/bindings</a></code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Alternative, to see a single binding, access one of the URLs similar to the following:
|
||
<code><a href="http://<host>:<port>/actuator/bindings/<bindingName>" class="bare">http://<host>:<port>/actuator/bindings/<bindingName></a>;</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also stop, start, pause, and resume individual bindings by posting to the same URL while providing a <code>state</code> argument as JSON, as shown in the following examples:</p>
|
||
</div>
|
||
<div class="literalblock">
|
||
<div class="content">
|
||
<pre>curl -d '{"state":"STOPPED"}' -H "Content-Type: application/json" -X POST http://<host>:<port>/actuator/bindings/myBindingName
|
||
curl -d '{"state":"STARTED"}' -H "Content-Type: application/json" -X POST http://<host>:<port>/actuator/bindings/myBindingName
|
||
curl -d '{"state":"PAUSED"}' -H "Content-Type: application/json" -X POST http://<host>:<port>/actuator/bindings/myBindingName
|
||
curl -d '{"state":"RESUMED"}' -H "Content-Type: application/json" -X POST http://<host>:<port>/actuator/bindings/myBindingName</pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
<code>PAUSED</code> and <code>RESUMED</code> work only when the corresponding binder and its underlying technology supports it. Otherwise, you see the warning message in the logs.
|
||
Currently, only Kafka binder supports the <code>PAUSED</code> and <code>RESUMED</code> states.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_binder_configuration_properties"><a class="link" href="#_binder_configuration_properties">Binder Configuration Properties</a></h3>
|
||
<div class="paragraph">
|
||
<p>The following properties are available when customizing binder configurations. These properties exposed via <code>org.springframework.cloud.stream.config.BinderProperties</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>They must be prefixed with <code>spring.cloud.stream.binders.<configurationName></code>.</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">type</dt>
|
||
<dd>
|
||
<p>The binder type.
|
||
It typically references one of the binders found on the classpath — in particular, a key in a <code>META-INF/spring.binders</code> file.</p>
|
||
<div class="paragraph">
|
||
<p>By default, it has the same value as the configuration name.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">inheritEnvironment</dt>
|
||
<dd>
|
||
<p>Whether the configuration inherits the environment of the application itself.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>true</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">environment</dt>
|
||
<dd>
|
||
<p>Root for a set of properties that can be used to customize the environment of the binder.
|
||
When this property is set, the context in which the binder is being created is not a child of the application context.
|
||
This setting allows for complete separation between the binder components and the application components.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>empty</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">defaultCandidate</dt>
|
||
<dd>
|
||
<p>Whether the binder configuration is a candidate for being considered a default binder or can be used only when explicitly referenced.
|
||
This setting allows adding binder configurations without interfering with the default processing.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>true</code>.</p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_configuration_options"><a class="link" href="#_configuration_options">Configuration Options</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream supports general configuration options as well as configuration for bindings and binders.
|
||
Some binders let additional binding properties support middleware-specific features.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Configuration options can be provided to Spring Cloud Stream applications through any mechanism supported by Spring Boot.
|
||
This includes application arguments, environment variables, and YAML or .properties files.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_binding_service_properties"><a class="link" href="#_binding_service_properties">Binding Service Properties</a></h3>
|
||
<div class="paragraph">
|
||
<p>These properties are exposed via <code>org.springframework.cloud.stream.config.BindingServiceProperties</code></p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">spring.cloud.stream.instanceCount</dt>
|
||
<dd>
|
||
<p>The number of deployed instances of an application.
|
||
Must be set for partitioning on the producer side. Must be set on the consumer side when using RabbitMQ and with Kafka if <code>autoRebalanceEnabled=false</code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>1</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.instanceIndex</dt>
|
||
<dd>
|
||
<p>The instance index of the application: A number from <code>0</code> to <code>instanceCount - 1</code>.
|
||
Used for partitioning with RabbitMQ and with Kafka if <code>autoRebalanceEnabled=false</code>.
|
||
Automatically set in Cloud Foundry to match the application’s instance index.</p>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.dynamicDestinations</dt>
|
||
<dd>
|
||
<p>A list of destinations that can be bound dynamically (for example, in a dynamic routing scenario).
|
||
If set, only listed destinations can be bound.</p>
|
||
<div class="paragraph">
|
||
<p>Default: empty (letting any destination be bound).</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.defaultBinder</dt>
|
||
<dd>
|
||
<p>The default binder to use, if multiple binders are configured.
|
||
See <a href="#multiple-binders">Multiple Binders on the Classpath</a>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: empty.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.overrideCloudConnectors</dt>
|
||
<dd>
|
||
<p>This property is only applicable when the <code>cloud</code> profile is active and Spring Cloud Connectors are provided with the application.
|
||
If the property is <code>false</code> (the default), the binder detects a suitable bound service (for example, a RabbitMQ service bound in Cloud Foundry for the RabbitMQ binder) and uses it for creating connections (usually through Spring Cloud Connectors).
|
||
When set to <code>true</code>, this property instructs binders to completely ignore the bound services and rely on Spring Boot properties (for example, relying on the <code>spring.rabbitmq.*</code> properties provided in the environment for the RabbitMQ binder).
|
||
The typical usage of this property is to be nested in a customized environment <a href="#multiple-systems">when connecting to multiple systems</a>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>false</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.bindingRetryInterval</dt>
|
||
<dd>
|
||
<p>The interval (in seconds) between retrying binding creation when, for example, the binder does not support late binding and the broker (for example, Apache Kafka) is down.
|
||
Set it to zero to treat such conditions as fatal, preventing the application from starting.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>30</code></p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="binding-properties"><a class="link" href="#binding-properties">Binding Properties</a></h3>
|
||
<div class="paragraph">
|
||
<p>Binding properties are supplied by using the format of <code>spring.cloud.stream.bindings.<channelName>.<property>=<value></code>.
|
||
The <code><channelName></code> represents the name of the channel being configured (for example, <code>output</code> for a <code>Source</code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To avoid repetition, Spring Cloud Stream supports setting values for all channels, in the format of <code>spring.cloud.stream.default.<property>=<value></code> for common binding properties, and <code>spring.cloud.stream.default.<producer|consumer>.<property>=<value></code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When it comes to avoiding repetitions for extended binding properties, this format should be used - <code>spring.cloud.stream.<binder-type>.default.<producer|consumer>.<property>=<value></code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In what follows, we indicate where we have omitted the <code>spring.cloud.stream.bindings.<channelName>.</code> prefix and focus just on the property name, with the understanding that the prefix is included at runtime.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_common_binding_properties"><a class="link" href="#_common_binding_properties">Common Binding Properties</a></h4>
|
||
<div class="paragraph">
|
||
<p>These properties are exposed via <code>org.springframework.cloud.stream.config.BindingProperties</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following binding properties are available for both input and output bindings and must be prefixed with <code>spring.cloud.stream.bindings.<channelName>.</code> (for example, <code>spring.cloud.stream.bindings.input.destination=ticktock</code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Default values can be set by using the <code>spring.cloud.stream.default</code> prefix (for example`spring.cloud.stream.default.contentType=application/json`).</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">destination</dt>
|
||
<dd>
|
||
<p>The target destination of a channel on the bound middleware (for example, the RabbitMQ exchange or Kafka topic).
|
||
If the channel is bound as a consumer, it could be bound to multiple destinations, and the destination names can be specified as comma-separated <code>String</code> values.
|
||
If not set, the channel name is used instead.
|
||
The default value of this property cannot be overridden.</p>
|
||
</dd>
|
||
<dt class="hdlist1">group</dt>
|
||
<dd>
|
||
<p>The consumer group of the channel.
|
||
Applies only to inbound bindings.
|
||
See <a href="#consumer-groups">Consumer Groups</a>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>null</code> (indicating an anonymous consumer).</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">contentType</dt>
|
||
<dd>
|
||
<p>The content type of the channel.
|
||
See <code><a href="#content-type-management">Content Type Negotiation</a></code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>application/json</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">binder</dt>
|
||
<dd>
|
||
<p>The binder used by this binding.
|
||
See <code><a href="#multiple-binders">Multiple Binders on the Classpath</a></code> for details.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>null</code> (the default binder is used, if it exists).</p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_consumer_properties"><a class="link" href="#_consumer_properties">Consumer Properties</a></h4>
|
||
<div class="paragraph">
|
||
<p>These properties are exposed via <code>org.springframework.cloud.stream.binder.ConsumerProperties</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following binding properties are available for input bindings only and must be prefixed with <code>spring.cloud.stream.bindings.<channelName>.consumer.</code> (for example, <code>spring.cloud.stream.bindings.input.consumer.concurrency=3</code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Default values can be set by using the <code>spring.cloud.stream.default.consumer</code> prefix (for example, <code>spring.cloud.stream.default.consumer.headerMode=none</code>).</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">autoStartup</dt>
|
||
<dd>
|
||
<p>Signals if this consumer needs to be started automatically</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>true</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">concurrency</dt>
|
||
<dd>
|
||
<p>The concurrency of the inbound consumer.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>1</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">partitioned</dt>
|
||
<dd>
|
||
<p>Whether the consumer receives data from a partitioned producer.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>false</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">headerMode</dt>
|
||
<dd>
|
||
<p>When set to <code>none</code>, disables header parsing on input.
|
||
Effective only for messaging middleware that does not support message headers natively and requires header embedding.
|
||
This option is useful when consuming data from non-Spring Cloud Stream applications when native headers are not supported.
|
||
When set to <code>headers</code>, it uses the middleware’s native header mechanism.
|
||
When set to <code>embeddedHeaders</code>, it embeds headers into the message payload.</p>
|
||
<div class="paragraph">
|
||
<p>Default: depends on the binder implementation.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">maxAttempts</dt>
|
||
<dd>
|
||
<p>If processing fails, the number of attempts to process the message (including the first).
|
||
Set to <code>1</code> to disable retry.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>3</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">backOffInitialInterval</dt>
|
||
<dd>
|
||
<p>The backoff initial interval on retry.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>1000</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">backOffMaxInterval</dt>
|
||
<dd>
|
||
<p>The maximum backoff interval.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>10000</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">backOffMultiplier</dt>
|
||
<dd>
|
||
<p>The backoff multiplier.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>2.0</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">defaultRetryable</dt>
|
||
<dd>
|
||
<p>Whether exceptions thrown by the listener that are not listed in the <code>retryableExceptions</code> are retryable.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>true</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">instanceIndex</dt>
|
||
<dd>
|
||
<p>When set to a value greater than equal to zero, it allows customizing the instance index of this consumer (if different from <code>spring.cloud.stream.instanceIndex</code>).
|
||
When set to a negative value, it defaults to <code>spring.cloud.stream.instanceIndex</code>.
|
||
See <code><a href="#spring-cloud-stream-overview-instance-index-instance-count">Instance Index and Instance Count</a></code> for more information.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>-1</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">instanceCount</dt>
|
||
<dd>
|
||
<p>When set to a value greater than equal to zero, it allows customizing the instance count of this consumer (if different from <code>spring.cloud.stream.instanceCount</code>).
|
||
When set to a negative value, it defaults to <code>spring.cloud.stream.instanceCount</code>.
|
||
See <code><a href="#spring-cloud-stream-overview-instance-index-instance-count">Instance Index and Instance Count</a></code> for more information.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>-1</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">retryableExceptions</dt>
|
||
<dd>
|
||
<p>A map of Throwable class names in the key and a boolean in the value.
|
||
Specify those exceptions (and subclasses) that will or won’t be retried.
|
||
Also see <code>defaultRetriable</code>.
|
||
Example: <code>spring.cloud.stream.bindings.input.consumer.retryable-exceptions.java.lang.IllegalStateException=false</code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: empty.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">useNativeDecoding</dt>
|
||
<dd>
|
||
<p>When set to <code>true</code>, the inbound message is deserialized directly by the client library, which must be configured correspondingly (for example, setting an appropriate Kafka producer value deserializer).
|
||
When this configuration is being used, the inbound message unmarshalling is not based on the <code>contentType</code> of the binding.
|
||
When native decoding is used, it is the responsibility of the producer to use an appropriate encoder (for example, the Kafka producer value serializer) to serialize the outbound message.
|
||
Also, when native encoding and decoding is used, the <code>headerMode=embeddedHeaders</code> property is ignored and headers are not embedded in the message.
|
||
See the producer property <code>useNativeEncoding</code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>false</code>.</p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_advanced_consumer_configuration"><a class="link" href="#_advanced_consumer_configuration">Advanced Consumer Configuration</a></h4>
|
||
<div class="paragraph">
|
||
<p>For advanced configuration of the underlying message listener container for message-driven consumers, add a single <code>ListenerContainerCustomizer</code> bean to the application context.
|
||
It will be invoked after the above properties have been applied and can be used to set additional properties.
|
||
Similarly, for polled consumers, add a <code>MessageSourceCustomizer</code> bean.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following is an example for the RabbitMQ binder:</p>
|
||
</div>
|
||
<div class="exampleblock">
|
||
<div class="content">
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public ListenerContainerCustomizer<AbstractMessageListenerContainer> containerCustomizer() {
|
||
return (container, dest, group) -> container.setAdviceChain(advice1, advice2);
|
||
}
|
||
|
||
@Bean
|
||
public MessageSourceCustomizer<AmqpMessageSource> sourceCustomizer() {
|
||
return (source, dest, group) -> source.setPropertiesConverter(customPropertiesConverter);
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_producer_properties"><a class="link" href="#_producer_properties">Producer Properties</a></h4>
|
||
<div class="paragraph">
|
||
<p>These properties are exposed via <code>org.springframework.cloud.stream.binder.ProducerProperties</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following binding properties are available for output bindings only and must be prefixed with <code>spring.cloud.stream.bindings.<channelName>.producer.</code> (for example, <code>spring.cloud.stream.bindings.input.producer.partitionKeyExpression=payload.id</code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Default values can be set by using the prefix <code>spring.cloud.stream.default.producer</code> (for example, <code>spring.cloud.stream.default.producer.partitionKeyExpression=payload.id</code>).</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">autoStartup</dt>
|
||
<dd>
|
||
<p>Signals if this consumer needs to be started automatically</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>true</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">partitionKeyExpression</dt>
|
||
<dd>
|
||
<p>A SpEL expression that determines how to partition outbound data.
|
||
If set, outbound data on this channel is partitioned. <code>partitionCount</code> must be set to a value greater than 1 to be effective.
|
||
See <code><a href="#partitioning">Partitioning Support</a></code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: null.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">partitionSelectorExpression</dt>
|
||
<dd>
|
||
<p>A SpEL expression for customizing partition selection.
|
||
If neither is set, the partition is selected as the <code>hashCode(key) % partitionCount</code>, where <code>key</code> is computed through either <code>partitionKeyExpression</code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>null</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">partitionCount</dt>
|
||
<dd>
|
||
<p>The number of target partitions for the data, if partitioning is enabled.
|
||
Must be set to a value greater than 1 if the producer is partitioned.
|
||
On Kafka, it is interpreted as a hint. The larger of this and the partition count of the target topic is used instead.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>1</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">requiredGroups</dt>
|
||
<dd>
|
||
<p>A comma-separated list of groups to which the producer must ensure message delivery even if they start after it has been created (for example, by pre-creating durable queues in RabbitMQ).</p>
|
||
</dd>
|
||
<dt class="hdlist1">headerMode</dt>
|
||
<dd>
|
||
<p>When set to <code>none</code>, it disables header embedding on output.
|
||
It is effective only for messaging middleware that does not support message headers natively and requires header embedding.
|
||
This option is useful when producing data for non-Spring Cloud Stream applications when native headers are not supported.
|
||
When set to <code>headers</code>, it uses the middleware’s native header mechanism.
|
||
When set to <code>embeddedHeaders</code>, it embeds headers into the message payload.</p>
|
||
<div class="paragraph">
|
||
<p>Default: Depends on the binder implementation.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">useNativeEncoding</dt>
|
||
<dd>
|
||
<p>When set to <code>true</code>, the outbound message is serialized directly by the client library, which must be configured correspondingly (for example, setting an appropriate Kafka producer value serializer).
|
||
When this configuration is being used, the outbound message marshalling is not based on the <code>contentType</code> of the binding.
|
||
When native encoding is used, it is the responsibility of the consumer to use an appropriate decoder (for example, the Kafka consumer value de-serializer) to deserialize the inbound message.
|
||
Also, when native encoding and decoding is used, the <code>headerMode=embeddedHeaders</code> property is ignored and headers are not embedded in the message.
|
||
See the consumer property <code>useNativeDecoding</code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>false</code>.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">errorChannelEnabled</dt>
|
||
<dd>
|
||
<p>When set to <code>true</code>, if the binder supports asynchroous send results, send failures are sent to an error channel for the destination.
|
||
See <code><a href="#spring-cloud-stream-overview-error-handling">Error Handling</a></code> for more information.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>false</code>.</p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="dynamicdestination"><a class="link" href="#dynamicdestination">Using Dynamically Bound Destinations</a></h3>
|
||
<div class="paragraph">
|
||
<p>Besides the channels defined by using <code>@EnableBinding</code>, Spring Cloud Stream lets applications send messages to dynamically bound destinations.
|
||
This is useful, for example, when the target destination needs to be determined at runtime.
|
||
Applications can do so by using the <code>BinderAwareChannelResolver</code> bean, registered automatically by the <code>@EnableBinding</code> annotation.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The 'spring.cloud.stream.dynamicDestinations' property can be used for restricting the dynamic destination names to a known set (whitelisting).
|
||
If this property is not set, any destination can be bound dynamically.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>BinderAwareChannelResolver</code> can be used directly, as shown in the following example of a REST controller using a path variable to decide the target channel:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding
|
||
@Controller
|
||
public class SourceWithDynamicDestination {
|
||
|
||
@Autowired
|
||
private BinderAwareChannelResolver resolver;
|
||
|
||
@RequestMapping(path = "/{target}", method = POST, consumes = "*/*")
|
||
@ResponseStatus(HttpStatus.ACCEPTED)
|
||
public void handleRequest(@RequestBody String body, @PathVariable("target") target,
|
||
@RequestHeader(HttpHeaders.CONTENT_TYPE) Object contentType) {
|
||
sendMessage(body, target, contentType);
|
||
}
|
||
|
||
private void sendMessage(String body, String target, Object contentType) {
|
||
resolver.resolveDestination(target).send(MessageBuilder.createMessage(body,
|
||
new MessageHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, contentType))));
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now consider what happens when we start the application on the default port (8080) and make the following requests with CURL:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>curl -H "Content-Type: application/json" -X POST -d "customer-1" http://localhost:8080/customers
|
||
|
||
curl -H "Content-Type: application/json" -X POST -d "order-1" http://localhost:8080/orders</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The destinations, 'customers' and 'orders', are created in the broker (in the exchange for Rabbit or in the topic for Kafka) with names of 'customers' and 'orders', and the data is published to the appropriate destinations.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>BinderAwareChannelResolver</code> is a general-purpose Spring Integration <code>DestinationResolver</code> and can be injected in other components — for example, in a router using a SpEL expression based on the <code>target</code> field of an incoming JSON message. The following example includes a router that reads SpEL expressions:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding
|
||
@Controller
|
||
public class SourceWithDynamicDestination {
|
||
|
||
@Autowired
|
||
private BinderAwareChannelResolver resolver;
|
||
|
||
|
||
@RequestMapping(path = "/", method = POST, consumes = "application/json")
|
||
@ResponseStatus(HttpStatus.ACCEPTED)
|
||
public void handleRequest(@RequestBody String body, @RequestHeader(HttpHeaders.CONTENT_TYPE) Object contentType) {
|
||
sendMessage(body, contentType);
|
||
}
|
||
|
||
private void sendMessage(Object body, Object contentType) {
|
||
routerChannel().send(MessageBuilder.createMessage(body,
|
||
new MessageHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, contentType))));
|
||
}
|
||
|
||
@Bean(name = "routerChannel")
|
||
public MessageChannel routerChannel() {
|
||
return new DirectChannel();
|
||
}
|
||
|
||
@Bean
|
||
@ServiceActivator(inputChannel = "routerChannel")
|
||
public ExpressionEvaluatingRouter router() {
|
||
ExpressionEvaluatingRouter router =
|
||
new ExpressionEvaluatingRouter(new SpelExpressionParser().parseExpression("payload.target"));
|
||
router.setDefaultOutputChannelName("default-output");
|
||
router.setChannelResolver(resolver);
|
||
return router;
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <a href="https://github.com/spring-cloud-stream-app-starters/router">Router Sink Application</a> uses this technique to create the destinations on-demand.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If the channel names are known in advance, you can configure the producer properties as with any other destination.
|
||
Alternatively, if you register a <code>NewDestinationBindingCallback<></code> bean, it is invoked just before the binding is created.
|
||
The callback takes the generic type of the extended producer properties used by the binder.
|
||
It has one method:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">void configure(String channelName, MessageChannel channel, ProducerProperties producerProperties,
|
||
T extendedProducerProperties);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to use the RabbitMQ binder:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public NewDestinationBindingCallback<RabbitProducerProperties> dynamicConfigurer() {
|
||
return (name, channel, props, extended) -> {
|
||
props.setRequiredGroups("bindThisQueue");
|
||
extended.setQueueNameGroupOnly(true);
|
||
extended.setAutoBindDlq(true);
|
||
extended.setDeadLetterQueueName("myDLQ");
|
||
};
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
If you need to support dynamic destinations with multiple binder types, use <code>Object</code> for the generic type and cast the <code>extended</code> argument as needed.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="content-type-management"><a class="link" href="#content-type-management">Content Type Negotiation</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Data transformation is one of the core features of any message-driven microservice architecture. Given that, in Spring Cloud Stream, such data
|
||
is represented as a Spring <code>Message</code>, a message may have to be transformed to a desired shape or size before reaching its destination. This is required for two reasons:</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p>To convert the contents of the incoming message to match the signature of the application-provided handler.</p>
|
||
</li>
|
||
<li>
|
||
<p>To convert the contents of the outgoing message to the wire format.</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The wire format is typically <code>byte[]</code> (that is true for the Kafka and Rabbit binders), but it is governed by the binder implementation.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In Spring Cloud Stream, message transformation is accomplished with an <code>org.springframework.messaging.converter.MessageConverter</code>.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
As a supplement to the details to follow, you may also want to read the following <a href="https://spring.io/blog/2018/02/26/spring-cloud-stream-2-0-content-type-negotiation-and-transformation">blog post</a>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_mechanics"><a class="link" href="#_mechanics">Mechanics</a></h3>
|
||
<div class="paragraph">
|
||
<p>To better understand the mechanics and the necessity behind content-type negotiation, we take a look at a very simple use case by using the following message handler as an example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@StreamListener(Processor.INPUT)
|
||
@SendTo(Processor.OUTPUT)
|
||
public String handle(Person person) {..}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
For simplicity, we assume that this is the only handler in the application (we assume there is no internal pipeline).
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The handler shown in the preceding example expects a <code>Person</code> object as an argument and produces a <code>String</code> type as an output.
|
||
In order for the framework to succeed in passing the incoming <code>Message</code> as an argument to this handler, it has to somehow transform the payload of the <code>Message</code> type from the wire format to a <code>Person</code> type.
|
||
In other words, the framework must locate and apply the appropriate <code>MessageConverter</code>.
|
||
To accomplish that, the framework needs some instructions from the user.
|
||
One of these instructions is already provided by the signature of the handler method itself (<code>Person</code> type).
|
||
Consequently, in theory, that should be (and, in some cases, is) enough.
|
||
However, for the majority of use cases, in order to select the appropriate <code>MessageConverter</code>, the framework needs an additional piece of information.
|
||
That missing piece is <code>contentType</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides three mechanisms to define <code>contentType</code> (in order of precedence):</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p><strong>HEADER</strong>: The <code>contentType</code> can be communicated through the Message itself. By providing a <code>contentType</code> header, you declare the content type to use to locate and apply the appropriate <code>MessageConverter</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p><strong>BINDING</strong>: The <code>contentType</code> can be set per destination binding by setting the <code>spring.cloud.stream.bindings.input.content-type</code> property.</p>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The <code>input</code> segment in the property name corresponds to the actual name of the destination (which is “input” in our case). This approach lets you declare, on a per-binding basis, the content type to use to locate and apply the appropriate <code>MessageConverter</code>.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</li>
|
||
<li>
|
||
<p><strong>DEFAULT</strong>: If <code>contentType</code> is not present in the <code>Message</code> header or the binding, the default <code>application/json</code> content type is used to
|
||
locate and apply the appropriate <code>MessageConverter</code>.</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As mentioned earlier, the preceding list also demonstrates the order of precedence in case of a tie. For example, a header-provided content type takes precedence over any other content type.
|
||
The same applies for a content type set on a per-binding basis, which essentially lets you override the default content type.
|
||
However, it also provides a sensible default (which was determined from community feedback).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Another reason for making <code>application/json</code> the default stems from the interoperability requirements driven by distributed microservices architectures, where producer and consumer not only run in different JVMs but can also run on different non-JVM platforms.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When the non-void handler method returns, if the return value is already a <code>Message</code>, that <code>Message</code> becomes the payload. However, when the return value is not a <code>Message</code>, the new <code>Message</code> is constructed with the return value as the payload while inheriting
|
||
headers from the input <code>Message</code> minus the headers defined or filtered by <code>SpringIntegrationProperties.messageHandlerNotPropagatedHeaders</code>.
|
||
By default, there is only one header set there: <code>contentType</code>. This means that the new <code>Message</code> does not have <code>contentType</code> header set, thus ensuring that the <code>contentType</code> can evolve.
|
||
You can always opt out of returning a <code>Message</code> from the handler method where you can inject any header you wish.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If there is an internal pipeline, the <code>Message</code> is sent to the next handler by going through the same process of conversion. However, if there is no internal pipeline or you have reached the end of it, the <code>Message</code> is sent back to the output destination.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_content_type_versus_argument_type"><a class="link" href="#_content_type_versus_argument_type">Content Type versus Argument Type</a></h4>
|
||
<div class="paragraph">
|
||
<p>As mentioned earlier, for the framework to select the appropriate <code>MessageConverter</code>, it requires argument type and, optionally, content type information.
|
||
The logic for selecting the appropriate <code>MessageConverter</code> resides with the argument resolvers (<code>HandlerMethodArgumentResolvers</code>), which trigger right before the invocation of the user-defined handler method (which is when the actual argument type is known to the framework).
|
||
If the argument type does not match the type of the current payload, the framework delegates to the stack of the
|
||
pre-configured <code>MessageConverters</code> to see if any one of them can convert the payload.
|
||
As you can see, the <code>Object fromMessage(Message<?> message, Class<?> targetClass);</code>
|
||
operation of the MessageConverter takes <code>targetClass</code> as one of its arguments.
|
||
The framework also ensures that the provided <code>Message</code> always contains a <code>contentType</code> header.
|
||
When no contentType header was already present, it injects either the per-binding <code>contentType</code> header or the default <code>contentType</code> header.
|
||
The combination of <code>contentType</code> argument type is the mechanism by which framework determines if message can be converted to a target type.
|
||
If no appropriate <code>MessageConverter</code> is found, an exception is thrown, which you can handle by adding a custom <code>MessageConverter</code> (see <code><a href="#spring-cloud-stream-overview-user-defined-message-converters">User-defined Message Converters</a></code>).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>But what if the payload type matches the target type declared by the handler method? In this case, there is nothing to convert, and the
|
||
payload is passed unmodified. While this sounds pretty straightforward and logical, keep in mind handler methods that take a <code>Message<?></code> or <code>Object</code> as an argument.
|
||
By declaring the target type to be <code>Object</code> (which is an <code>instanceof</code> everything in Java), you essentially forfeit the conversion process.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Do not expect <code>Message</code> to be converted into some other type based only on the <code>contentType</code>.
|
||
Remember that the <code>contentType</code> is complementary to the target type.
|
||
If you wish, you can provide a hint, which <code>MessageConverter</code> may or may not take into consideration.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_message_converters"><a class="link" href="#_message_converters">Message Converters</a></h4>
|
||
<div class="paragraph">
|
||
<p><code>MessageConverters</code> define two methods:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">Object fromMessage(Message<?> message, Class<?> targetClass);
|
||
|
||
Message<?> toMessage(Object payload, @Nullable MessageHeaders headers);</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>It is important to understand the contract of these methods and their usage, specifically in the context of Spring Cloud Stream.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>fromMessage</code> method converts an incoming <code>Message</code> to an argument type.
|
||
The payload of the <code>Message</code> could be any type, and it is
|
||
up to the actual implementation of the <code>MessageConverter</code> to support multiple types.
|
||
For example, some JSON converter may support the payload type as <code>byte[]</code>, <code>String</code>, and others.
|
||
This is important when the application contains an internal pipeline (that is, input → handler1 → handler2 →. . . → output) and the output of the upstream handler results in a <code>Message</code> which may not be in the initial wire format.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>However, the <code>toMessage</code> method has a more strict contract and must always convert <code>Message</code> to the wire format: <code>byte[]</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>So, for all intents and purposes (and especially when implementing your own converter) you regard the two methods as having the following signatures:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">Object fromMessage(Message<?> message, Class<?> targetClass);
|
||
|
||
Message<byte[]> toMessage(Object payload, @Nullable MessageHeaders headers);</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_provided_messageconverters"><a class="link" href="#_provided_messageconverters">Provided MessageConverters</a></h3>
|
||
<div class="paragraph">
|
||
<p>As mentioned earlier, the framework already provides a stack of <code>MessageConverters</code> to handle most common use cases.
|
||
The following list describes the provided <code>MessageConverters</code>, in order of precedence (the first <code>MessageConverter</code> that works is used):</p>
|
||
</div>
|
||
<div class="olist arabic">
|
||
<ol class="arabic">
|
||
<li>
|
||
<p><code>ApplicationJsonMessageMarshallingConverter</code>: Variation of the <code>org.springframework.messaging.converter.MappingJackson2MessageConverter</code>. Supports conversion of the payload of the <code>Message</code> to/from POJO for cases when <code>contentType</code> is <code>application/json</code> (DEFAULT).</p>
|
||
</li>
|
||
<li>
|
||
<p><code>TupleJsonMessageConverter</code>: <strong>DEPRECATED</strong> Supports conversion of the payload of the <code>Message</code> to/from <code>org.springframework.tuple.Tuple</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>ByteArrayMessageConverter</code>: Supports conversion of the payload of the <code>Message</code> from <code>byte[]</code> to <code>byte[]</code> for cases when <code>contentType</code> is <code>application/octet-stream</code>. It is essentially a pass through and exists primarily for backward compatibility.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>ObjectStringMessageConverter</code>: Supports conversion of any type to a <code>String</code> when <code>contentType</code> is <code>text/plain</code>.
|
||
It invokes Object’s <code>toString()</code> method or, if the payload is <code>byte[]</code>, a new <code>String(byte[])</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>JavaSerializationMessageConverter</code>: <strong>DEPRECATED</strong> Supports conversion based on java serialization when <code>contentType</code> is <code>application/x-java-serialized-object</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>KryoMessageConverter</code>: <strong>DEPRECATED</strong> Supports conversion based on Kryo serialization when <code>contentType</code> is <code>application/x-java-object</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p><code>JsonUnmarshallingConverter</code>: Similar to the <code>ApplicationJsonMessageMarshallingConverter</code>. It supports conversion of any type when <code>contentType</code> is <code>application/x-java-object</code>.
|
||
It expects the actual type information to be embedded in the <code>contentType</code> as an attribute (for example, <code>application/x-java-object;type=foo.bar.Cat</code>).</p>
|
||
</li>
|
||
</ol>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When no appropriate converter is found, the framework throws an exception. When that happens, you should check your code and configuration and ensure you did not miss anything (that is, ensure that you provided a <code>contentType</code> by using a binding or a header).
|
||
However, most likely, you found some uncommon case (such as a custom <code>contentType</code> perhaps) and the current stack of provided <code>MessageConverters</code>
|
||
does not know how to convert. If that is the case, you can add custom <code>MessageConverter</code>. See <a href="#spring-cloud-stream-overview-user-defined-message-converters">User-defined Message Converters</a>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-user-defined-message-converters"><a class="link" href="#spring-cloud-stream-overview-user-defined-message-converters">User-defined Message Converters</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream exposes a mechanism to define and register additional <code>MessageConverters</code>.
|
||
To use it, implement <code>org.springframework.messaging.converter.MessageConverter</code>, configure it as a <code>@Bean</code>, and annotate it with <code>@StreamMessageConverter</code>.
|
||
It is then apended to the existing stack of `MessageConverter`s.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
It is important to understand that custom <code>MessageConverter</code> implementations are added to the head of the existing stack.
|
||
Consequently, custom <code>MessageConverter</code> implementations take precedence over the existing ones, which lets you override as well as add to the existing converters.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to create a message converter bean to support a new content type called <code>application/bar</code>:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Sink.class)
|
||
@SpringBootApplication
|
||
public static class SinkApplication {
|
||
|
||
...
|
||
|
||
@Bean
|
||
@StreamMessageConverter
|
||
public MessageConverter customMessageConverter() {
|
||
return new MyCustomMessageConverter();
|
||
}
|
||
}
|
||
|
||
public class MyCustomMessageConverter extends AbstractMessageConverter {
|
||
|
||
public MyCustomMessageConverter() {
|
||
super(new MimeType("application", "bar"));
|
||
}
|
||
|
||
@Override
|
||
protected boolean supports(Class<?> clazz) {
|
||
return (Bar.class.equals(clazz));
|
||
}
|
||
|
||
@Override
|
||
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, Object conversionHint) {
|
||
Object payload = message.getPayload();
|
||
return (payload instanceof Bar ? payload : new Bar((byte[]) payload));
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream also provides support for Avro-based converters and schema evolution.
|
||
See <code><a href="#schema-evolution">Schema Evolution Support</a></code> for details.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="schema-evolution"><a class="link" href="#schema-evolution">Schema Evolution Support</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides support for schema evolution so that the data can be evolved over time and still work with older or newer producers and consumers and vice versa.
|
||
Most serialization models, especially the ones that aim for portability across different platforms and languages, rely on a schema that describes how the data is serialized in the binary payload.
|
||
In order to serialize the data and then to interpret it, both the sending and receiving sides must have access to a schema that describes the binary format.
|
||
In certain cases, the schema can be inferred from the payload type on serialization or from the target type on deserialization.
|
||
However, many applications benefit from having access to an explicit schema that describes the binary data format.
|
||
A schema registry lets you store schema information in a textual format (typically JSON) and makes that information accessible to various applications that need it to receive and send data in binary format.
|
||
A schema is referenceable as a tuple consisting of:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>A subject that is the logical name of the schema</p>
|
||
</li>
|
||
<li>
|
||
<p>The schema version</p>
|
||
</li>
|
||
<li>
|
||
<p>The schema format, which describes the binary format of the data</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>This following sections goes through the details of various components involved in schema evolution process.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_schema_registry_client"><a class="link" href="#_schema_registry_client">Schema Registry Client</a></h3>
|
||
<div class="paragraph">
|
||
<p>The client-side abstraction for interacting with schema registry servers is the <code>SchemaRegistryClient</code> interface, which has the following structure:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public interface SchemaRegistryClient {
|
||
|
||
SchemaRegistrationResponse register(String subject, String format, String schema);
|
||
|
||
String fetch(SchemaReference schemaReference);
|
||
|
||
String fetch(Integer id);
|
||
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides out-of-the-box implementations for interacting with its own schema server and for interacting with the Confluent Schema Registry.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A client for the Spring Cloud Stream schema registry can be configured by using the <code>@EnableSchemaRegistryClient</code>, as follows:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> @EnableBinding(Sink.class)
|
||
@SpringBootApplication
|
||
@EnableSchemaRegistryClient
|
||
public static class AvroSinkApplication {
|
||
...
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The default converter is optimized to cache not only the schemas from the remote server but also the <code>parse()</code> and <code>toString()</code> methods, which are quite expensive.
|
||
Because of this, it uses a <code>DefaultSchemaRegistryClient</code> that does not cache responses.
|
||
If you intend to change the default behavior, you can use the client directly on your code and override it to the desired outcome.
|
||
To do so, you have to add the property <code>spring.cloud.stream.schemaRegistryClient.cached=true</code> to your application properties.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_schema_registry_client_properties"><a class="link" href="#_schema_registry_client_properties">Schema Registry Client Properties</a></h4>
|
||
<div class="paragraph">
|
||
<p>The Schema Registry Client supports the following properties:</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1"><code>spring.cloud.stream.schemaRegistryClient.endpoint</code></dt>
|
||
<dd>
|
||
<p>The location of the schema-server.
|
||
When setting this, use a full URL, including protocol (<code>http</code> or <code>https</code>) , port, and context path.</p>
|
||
</dd>
|
||
<dt class="hdlist1">Default</dt>
|
||
<dd>
|
||
<p><code><a href="http://localhost:8990/" class="bare">http://localhost:8990/</a></code></p>
|
||
</dd>
|
||
<dt class="hdlist1"><code>spring.cloud.stream.schemaRegistryClient.cached</code></dt>
|
||
<dd>
|
||
<p>Whether the client should cache schema server responses.
|
||
Normally set to <code>false</code>, as the caching happens in the message converter.
|
||
Clients using the schema registry client should set this to <code>true</code>.</p>
|
||
</dd>
|
||
<dt class="hdlist1">Default</dt>
|
||
<dd>
|
||
<p><code>false</code></p>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_avro_schema_registry_client_message_converters"><a class="link" href="#_avro_schema_registry_client_message_converters">Avro Schema Registry Client Message Converters</a></h3>
|
||
<div class="paragraph">
|
||
<p>For applications that have a SchemaRegistryClient bean registered with the application context, Spring Cloud Stream auto configures an Apache Avro message converter for schema management.
|
||
This eases schema evolution, as applications that receive messages can get easy access to a writer schema that can be reconciled with their own reader schema.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For outbound messages, if the content type of the channel is set to <code>application/*+avro</code>, the <code>MessageConverter</code> is activated, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-properties hljs" data-lang="properties">spring.cloud.stream.bindings.output.contentType=application/*+avro</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>During the outbound conversion, the message converter tries to infer the schema of each outbound messages (based on its type) and register it to a subject (based on the payload type) by using the <code>SchemaRegistryClient</code>.
|
||
If an identical schema is already found, then a reference to it is retrieved.
|
||
If not, the schema is registered, and a new version number is provided.
|
||
The message is sent with a <code>contentType</code> header by using the following scheme: <code>application/[prefix].[subject].v[version]+avro</code>, where <code>prefix</code> is configurable and <code>subject</code> is deduced from the payload type.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example, a message of the type <code>User</code> might be sent as a binary payload with a content type of <code>application/vnd.user.v2+avro</code>, where <code>user</code> is the subject and <code>2</code> is the version number.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When receiving messages, the converter infers the schema reference from the header of the incoming message and tries to retrieve it. The schema is used as the writer schema in the deserialization process.</p>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_avro_schema_registry_message_converter_properties"><a class="link" href="#_avro_schema_registry_message_converter_properties">Avro Schema Registry Message Converter Properties</a></h4>
|
||
<div class="paragraph">
|
||
<p>If you have enabled Avro based schema registry client by setting <code>spring.cloud.stream.bindings.output.contentType=application/*+avro</code>, you can customize the behavior of the registration by setting the following properties.</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">spring.cloud.stream.schema.avro.dynamicSchemaGenerationEnabled</dt>
|
||
<dd>
|
||
<p>Enable if you want the converter to use reflection to infer a Schema from a POJO.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>false</code></p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.schema.avro.readerSchema</dt>
|
||
<dd>
|
||
<p>Avro compares schema versions by looking at a writer schema (origin payload) and a reader schema (your application payload). See the <a href="https://avro.apache.org/docs/1.7.6/spec.html">Avro documentation</a> for more information. If set, this overrides any lookups at the schema server and uses the local schema as the reader schema.
|
||
Default: <code>null</code></p>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.schema.avro.schemaLocations</dt>
|
||
<dd>
|
||
<p>Registers any <code>.avsc</code> files listed in this property with the Schema Server.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>empty</code></p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.schema.avro.prefix</dt>
|
||
<dd>
|
||
<p>The prefix to be used on the Content-Type header.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>vnd</code></p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.schema.avro.subjectNamingStrategy</dt>
|
||
<dd>
|
||
<p>Determines the subject name used to register the Avro schema in the schema registry. Two implementations are available, <code>org.springframework.cloud.stream.schema.avro.DefaultSubjectNamingStrategy</code>,
|
||
where the subject is the schema name, and <code>org.springframework.cloud.stream.schema.avro.QualifiedSubjectNamingStrategy</code>, which returns a fully qualified subject using the Avro schema namespace and name. Custom strategies can be created by implementing <code>org.springframework.cloud.stream.schema.avro.SubjectNamingStrategy</code>.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>org.springframework.cloud.stream.schema.avro.DefaultSubjectNamingStrategy</code></p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_apache_avro_message_converters"><a class="link" href="#_apache_avro_message_converters">Apache Avro Message Converters</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides support for schema-based message converters through its <code>spring-cloud-stream-schema</code> module.
|
||
Currently, the only serialization format supported out of the box for schema-based message converters is Apache Avro, with more formats to be added in future versions.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>spring-cloud-stream-schema</code> module contains two types of message converters that can be used for Apache Avro serialization:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Converters that use the class information of the serialized or deserialized objects or a schema with a location known at startup.</p>
|
||
</li>
|
||
<li>
|
||
<p>Converters that use a schema registry. They locate the schemas at runtime and dynamically register new schemas as domain objects evolve.</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_converters_with_schema_support"><a class="link" href="#_converters_with_schema_support">Converters with Schema Support</a></h3>
|
||
<div class="paragraph">
|
||
<p>The <code>AvroSchemaMessageConverter</code> supports serializing and deserializing messages either by using a predefined schema or by using the schema information available in the class (either reflectively or contained in the <code>SpecificRecord</code>).
|
||
If you provide a custom converter, then the default AvroSchemaMessageConverter bean is not created. The following example shows a custom converter:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To use custom converters, you can simply add it to the application context, optionally specifying one or more <code>MimeTypes</code> with which to associate it.
|
||
The default <code>MimeType</code> is <code>application/avro</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If the target type of the conversion is a <code>GenericRecord</code>, a schema must be set.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows how to configure a converter in a sink application by registering the Apache Avro <code>MessageConverter</code> without a predefined schema.
|
||
In this example, note that the mime type value is <code>avro/bytes</code>, not the default <code>application/avro</code>.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Sink.class)
|
||
@SpringBootApplication
|
||
public static class SinkApplication {
|
||
|
||
...
|
||
|
||
@Bean
|
||
public MessageConverter userMessageConverter() {
|
||
return new AvroSchemaMessageConverter(MimeType.valueOf("avro/bytes"));
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Conversely, the following application registers a converter with a predefined schema (found on the classpath):</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@EnableBinding(Sink.class)
|
||
@SpringBootApplication
|
||
public static class SinkApplication {
|
||
|
||
...
|
||
|
||
@Bean
|
||
public MessageConverter userMessageConverter() {
|
||
AvroSchemaMessageConverter converter = new AvroSchemaMessageConverter(MimeType.valueOf("avro/bytes"));
|
||
converter.setSchemaLocation(new ClassPathResource("schemas/User.avro"));
|
||
return converter;
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_schema_registry_server"><a class="link" href="#_schema_registry_server">Schema Registry Server</a></h3>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides a schema registry server implementation.
|
||
To use it, you can add the <code>spring-cloud-stream-schema-server</code> artifact to your project and use the <code>@EnableSchemaRegistryServer</code> annotation, which adds the schema registry server REST controller to your application.
|
||
This annotation is intended to be used with Spring Boot web applications, and the listening port of the server is controlled by the <code>server.port</code> property.
|
||
The <code>spring.cloud.stream.schema.server.path</code> property can be used to control the root path of the schema server (especially when it is embedded in other applications).
|
||
The <code>spring.cloud.stream.schema.server.allowSchemaDeletion</code> boolean property enables the deletion of a schema. By default, this is disabled.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The schema registry server uses a relational database to store the schemas.
|
||
By default, it uses an embedded database.
|
||
You can customize the schema storage by using the <a href="http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-sql">Spring Boot SQL database and JDBC configuration options</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows a Spring Boot application that enables the schema registry:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableSchemaRegistryServer
|
||
public class SchemaRegistryServerApplication {
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(SchemaRegistryServerApplication.class, args);
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_schema_registry_server_api"><a class="link" href="#_schema_registry_server_api">Schema Registry Server API</a></h4>
|
||
<div class="paragraph">
|
||
<p>The Schema Registry Server API consists of the following operations:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>POST /</code> — see <code><a href="#spring-cloud-stream-overview-registering-new-schema">Registering a New Schema</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p>'GET /{subject}/{format}/{version}' — see <code><a href="#spring-cloud-stream-overview-retrieve-schema-subject-format-version">Retrieving an Existing Schema by Subject, Format, and Version</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>GET /{subject}/{format}</code> — see <code><a href="#spring-cloud-stream-overview-retrieve-schema-subject-format">Retrieving an Existing Schema by Subject and Format</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>GET /schemas/{id}</code> — see <code><a href="#spring-cloud-stream-overview-retrieve-schema-id">Retrieving an Existing Schema by ID</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>DELETE /{subject}/{format}/{version}</code> — see <code><a href="#spring-cloud-stream-overview-deleting-schema-subject-format-version">Deleting a Schema by Subject, Format, and Version</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>DELETE /schemas/{id}</code> — see <code><a href="#spring-cloud-stream-overview-deleting-schema-id">Deleting a Schema by ID</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code>DELETE /{subject}</code> — see <code><a href="#spring-cloud-stream-overview-deleting-schema-subject">Deleting a Schema by Subject</a></code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="spring-cloud-stream-overview-registering-new-schema"><a class="link" href="#spring-cloud-stream-overview-registering-new-schema">Registering a New Schema</a></h5>
|
||
<div class="paragraph">
|
||
<p>To register a new schema, send a <code>POST</code> request to the <code>/</code> endpoint.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>/</code> accepts a JSON payload with the following fields:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>subject</code>: The schema subject</p>
|
||
</li>
|
||
<li>
|
||
<p><code>format</code>: The schema format</p>
|
||
</li>
|
||
<li>
|
||
<p><code>definition</code>: The schema definition</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Its response is a schema object in JSON, with the following fields:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>id</code>: The schema ID</p>
|
||
</li>
|
||
<li>
|
||
<p><code>subject</code>: The schema subject</p>
|
||
</li>
|
||
<li>
|
||
<p><code>format</code>: The schema format</p>
|
||
</li>
|
||
<li>
|
||
<p><code>version</code>: The schema version</p>
|
||
</li>
|
||
<li>
|
||
<p><code>definition</code>: The schema definition</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="spring-cloud-stream-overview-retrieve-schema-subject-format-version"><a class="link" href="#spring-cloud-stream-overview-retrieve-schema-subject-format-version">Retrieving an Existing Schema by Subject, Format, and Version</a></h5>
|
||
<div class="paragraph">
|
||
<p>To retrieve an existing schema by subject, format, and version, send <code>GET</code> request to the <code>/{subject}/{format}/{version}</code> endpoint.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Its response is a schema object in JSON, with the following fields:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>id</code>: The schema ID</p>
|
||
</li>
|
||
<li>
|
||
<p><code>subject</code>: The schema subject</p>
|
||
</li>
|
||
<li>
|
||
<p><code>format</code>: The schema format</p>
|
||
</li>
|
||
<li>
|
||
<p><code>version</code>: The schema version</p>
|
||
</li>
|
||
<li>
|
||
<p><code>definition</code>: The schema definition</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="spring-cloud-stream-overview-retrieve-schema-subject-format"><a class="link" href="#spring-cloud-stream-overview-retrieve-schema-subject-format">Retrieving an Existing Schema by Subject and Format</a></h5>
|
||
<div class="paragraph">
|
||
<p>To retrieve an existing schema by subject and format, send a <code>GET</code> request to the <code>/subject/format</code> endpoint.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Its response is a list of schemas with each schema object in JSON, with the following fields:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>id</code>: The schema ID</p>
|
||
</li>
|
||
<li>
|
||
<p><code>subject</code>: The schema subject</p>
|
||
</li>
|
||
<li>
|
||
<p><code>format</code>: The schema format</p>
|
||
</li>
|
||
<li>
|
||
<p><code>version</code>: The schema version</p>
|
||
</li>
|
||
<li>
|
||
<p><code>definition</code>: The schema definition</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="spring-cloud-stream-overview-retrieve-schema-id"><a class="link" href="#spring-cloud-stream-overview-retrieve-schema-id">Retrieving an Existing Schema by ID</a></h5>
|
||
<div class="paragraph">
|
||
<p>To retrieve a schema by its ID, send a <code>GET</code> request to the <code>/schemas/{id}</code> endpoint.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Its response is a schema object in JSON, with the following fields:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code>id</code>: The schema ID</p>
|
||
</li>
|
||
<li>
|
||
<p><code>subject</code>: The schema subject</p>
|
||
</li>
|
||
<li>
|
||
<p><code>format</code>: The schema format</p>
|
||
</li>
|
||
<li>
|
||
<p><code>version</code>: The schema version</p>
|
||
</li>
|
||
<li>
|
||
<p><code>definition</code>: The schema definition</p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="spring-cloud-stream-overview-deleting-schema-subject-format-version"><a class="link" href="#spring-cloud-stream-overview-deleting-schema-subject-format-version">Deleting a Schema by Subject, Format, and Version</a></h5>
|
||
<div class="paragraph">
|
||
<p>To delete a schema identified by its subject, format, and version, send a <code>DELETE</code> request to the <code>/{subject}/{format}/{version}</code> endpoint.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="spring-cloud-stream-overview-deleting-schema-id"><a class="link" href="#spring-cloud-stream-overview-deleting-schema-id">Deleting a Schema by ID</a></h5>
|
||
<div class="paragraph">
|
||
<p>To delete a schema by its ID, send a <code>DELETE</code> request to the <code>/schemas/{id}</code> endpoint.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect4">
|
||
<h5 id="spring-cloud-stream-overview-deleting-schema-subject"><a class="link" href="#spring-cloud-stream-overview-deleting-schema-subject">Deleting a Schema by Subject</a></h5>
|
||
<div class="paragraph">
|
||
<p><code>DELETE /{subject}</code></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Delete existing schemas by their subject.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
This note applies to users of Spring Cloud Stream 1.1.0.RELEASE only.
|
||
Spring Cloud Stream 1.1.0.RELEASE used the table name, <code>schema</code>, for storing <code>Schema</code> objects. <code>Schema</code> is a keyword in a number of database implementations.
|
||
To avoid any conflicts in the future, starting with 1.1.1.RELEASE, we have opted for the name <code>SCHEMA_REPOSITORY</code> for the storage table.
|
||
Any Spring Cloud Stream 1.1.0.RELEASE users who upgrade should migrate their existing schemas to the new table before upgrading.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_using_confluents_schema_registry"><a class="link" href="#_using_confluents_schema_registry">Using Confluent’s Schema Registry</a></h4>
|
||
<div class="paragraph">
|
||
<p>The default configuration creates a <code>DefaultSchemaRegistryClient</code> bean.
|
||
If you want to use the Confluent schema registry, you need to create a bean of type <code>ConfluentSchemaRegistryClient</code>, which supersedes the one configured by default by the framework. The following example shows how to create such a bean:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public SchemaRegistryClient schemaRegistryClient(@Value("${spring.cloud.stream.schemaRegistryClient.endpoint}") String endpoint){
|
||
ConfluentSchemaRegistryClient client = new ConfluentSchemaRegistryClient();
|
||
client.setEndpoint(endpoint);
|
||
return client;
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The ConfluentSchemaRegistryClient is tested against Confluent platform version 4.0.0.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_schema_registration_and_resolution"><a class="link" href="#_schema_registration_and_resolution">Schema Registration and Resolution</a></h3>
|
||
<div class="paragraph">
|
||
<p>To better understand how Spring Cloud Stream registers and resolves new schemas and its use of Avro schema comparison features, we provide two separate subsections:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code><a href="#spring-cloud-stream-overview-schema-registration-process">Schema Registration Process (Serialization)</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><a href="#spring-cloud-stream-overview-schema-resolution-process">Schema Resolution Process (Deserialization)</a></code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-stream-overview-schema-registration-process"><a class="link" href="#spring-cloud-stream-overview-schema-registration-process">Schema Registration Process (Serialization)</a></h4>
|
||
<div class="paragraph">
|
||
<p>The first part of the registration process is extracting a schema from the payload that is being sent over a channel.
|
||
Avro types such as <code>SpecificRecord</code> or <code>GenericRecord</code> already contain a schema, which can be retrieved immediately from the instance.
|
||
In the case of POJOs, a schema is inferred if the <code>spring.cloud.stream.schema.avro.dynamicSchemaGenerationEnabled</code> property is set to <code>true</code> (the default).</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/schema_resolution.png" alt="schema resolution" width="800">
|
||
</div>
|
||
<div class="title">Figure 7. Schema Writer Resolution Process</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Ones a schema is obtained, the converter loads its metadata (version) from the remote server.
|
||
First, it queries a local cache. If no result is found, it submits the data to the server, which replies with versioning information.
|
||
The converter always caches the results to avoid the overhead of querying the Schema Server for every new message that needs to be serialized.</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/registration.png" alt="registration" width="800">
|
||
</div>
|
||
<div class="title">Figure 8. Schema Registration Process</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>With the schema version information, the converter sets the <code>contentType</code> header of the message to carry the version information — for example: <code>application/vnd.user.v1+avro</code>.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-stream-overview-schema-resolution-process"><a class="link" href="#spring-cloud-stream-overview-schema-resolution-process">Schema Resolution Process (Deserialization)</a></h4>
|
||
<div class="paragraph">
|
||
<p>When reading messages that contain version information (that is, a <code>contentType</code> header with a scheme like the one described under <code><a href="#spring-cloud-stream-overview-schema-registration-process">Schema Registration Process (Serialization)</a></code>, the converter queries the Schema server to fetch the writer schema of the message.
|
||
Once it has found the correct schema of the incoming message, it retrieves the reader schema and, by using Avro’s schema resolution support, reads it into the reader definition (setting defaults and any missing properties).</p>
|
||
</div>
|
||
<div class="imageblock" style="text-align: center">
|
||
<div class="content">
|
||
<img src="https://raw.githubusercontent.com/spring-cloud/spring-cloud-stream/master/docs/src/main/asciidoc/images/schema_reading.png" alt="schema reading" width="800">
|
||
</div>
|
||
<div class="title">Figure 9. Schema Reading Resolution Process</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
You should understand the difference between a writer schema (the application that wrote the message) and a reader schema (the receiving application).
|
||
We suggest taking a moment to read <a href="https://avro.apache.org/docs/1.7.6/spec.html">the Avro terminology</a> and understand the process.
|
||
Spring Cloud Stream always fetches the writer schema to determine how to read a message.
|
||
If you want to get Avro’s schema evolution support working, you need to make sure that a <code>readerSchema</code> was properly set for your application.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_inter_application_communication"><a class="link" href="#_inter_application_communication">Inter-Application Communication</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream enables communication between applications. Inter-application communication is a complex issue spanning several concerns, as described in the following topics:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code><a href="#spring-cloud-stream-overview-connecting-multiple-application-instances">Connecting Multiple Application Instances</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><a href="#spring-cloud-stream-overview-instance-index-instance-count">Instance Index and Instance Count</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><a href="#spring-cloud-stream-overview-partitioning">Partitioning</a></code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-connecting-multiple-application-instances"><a class="link" href="#spring-cloud-stream-overview-connecting-multiple-application-instances">Connecting Multiple Application Instances</a></h3>
|
||
<div class="paragraph">
|
||
<p>While Spring Cloud Stream makes it easy for individual Spring Boot applications to connect to messaging systems, the typical scenario for Spring Cloud Stream is the creation of multi-application pipelines, where microservice applications send data to each other.
|
||
You can achieve this scenario by correlating the input and output destinations of “adjacent” applications.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Suppose a design calls for the Time Source application to send data to the Log Sink application. You could use a common destination named <code>ticktock</code> for bindings within both applications.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Time Source (that has the channel name <code>output</code>) would set the following property:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>spring.cloud.stream.bindings.output.destination=ticktock</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Log Sink (that has the channel name <code>input</code>) would set the following property:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>spring.cloud.stream.bindings.input.destination=ticktock</pre>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-instance-index-instance-count"><a class="link" href="#spring-cloud-stream-overview-instance-index-instance-count">Instance Index and Instance Count</a></h3>
|
||
<div class="paragraph">
|
||
<p>When scaling up Spring Cloud Stream applications, each instance can receive information about how many other instances of the same application exist and what its own instance index is.
|
||
Spring Cloud Stream does this through the <code>spring.cloud.stream.instanceCount</code> and <code>spring.cloud.stream.instanceIndex</code> properties.
|
||
For example, if there are three instances of a HDFS sink application, all three instances have <code>spring.cloud.stream.instanceCount</code> set to <code>3</code>, and the individual applications have <code>spring.cloud.stream.instanceIndex</code> set to <code>0</code>, <code>1</code>, and <code>2</code>, respectively.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When Spring Cloud Stream applications are deployed through Spring Cloud Data Flow, these properties are configured automatically; when Spring Cloud Stream applications are launched independently, these properties must be set correctly.
|
||
By default, <code>spring.cloud.stream.instanceCount</code> is <code>1</code>, and <code>spring.cloud.stream.instanceIndex</code> is <code>0</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In a scaled-up scenario, correct configuration of these two properties is important for addressing partitioning behavior (see below) in general, and the two properties are always required by certain binders (for example, the Kafka binder) in order to ensure that data are split correctly across multiple consumer instances.</p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring-cloud-stream-overview-partitioning"><a class="link" href="#spring-cloud-stream-overview-partitioning">Partitioning</a></h3>
|
||
<div class="paragraph">
|
||
<p>Partitioning in Spring Cloud Stream consists of two tasks:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><code><a href="#spring-cloud-stream-overview-configuring-output-bindings-partitioning">Configuring Output Bindings for Partitioning</a></code></p>
|
||
</li>
|
||
<li>
|
||
<p><code><a href="#spring-cloud-stream-overview-configuring-input-bindings-partitioning">Configuring Input Bindings for Partitioning</a></code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-stream-overview-configuring-output-bindings-partitioning"><a class="link" href="#spring-cloud-stream-overview-configuring-output-bindings-partitioning">Configuring Output Bindings for Partitioning</a></h4>
|
||
<div class="paragraph">
|
||
<p>You can configure an output binding to send partitioned data by setting one and only one of its <code>partitionKeyExpression</code> or <code>partitionKeyExtractorName</code> properties, as well as its <code>partitionCount</code> property.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example, the following is a valid and typical configuration:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>spring.cloud.stream.bindings.output.producer.partitionKeyExpression=payload.id
|
||
spring.cloud.stream.bindings.output.producer.partitionCount=5</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Based on that example configuration, data is sent to the target partition by using the following logic.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>A partition key’s value is calculated for each message sent to a partitioned output channel based on the <code>partitionKeyExpression</code>.
|
||
The <code>partitionKeyExpression</code> is a SpEL expression that is evaluated against the outbound message for extracting the partitioning key.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If a SpEL expression is not sufficient for your needs, you can instead calculate the partition key value by providing an implementation of <code>org.springframework.cloud.stream.binder.PartitionKeyExtractorStrategy</code> and configuring it as a bean (by using the <code>@Bean</code> annotation).
|
||
If you have more then one bean of type <code>org.springframework.cloud.stream.binder.PartitionKeyExtractorStrategy</code> available in the Application Context, you can further filter it by specifying its name with the <code>partitionKeyExtractorName</code> property, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>--spring.cloud.stream.bindings.output.producer.partitionKeyExtractorName=customPartitionKeyExtractor
|
||
--spring.cloud.stream.bindings.output.producer.partitionCount=5
|
||
. . .
|
||
@Bean
|
||
public CustomPartitionKeyExtractorClass customPartitionKeyExtractor() {
|
||
return new CustomPartitionKeyExtractorClass();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
In previous versions of Spring Cloud Stream, you could specify the implementation of <code>org.springframework.cloud.stream.binder.PartitionKeyExtractorStrategy</code> by setting the <code>spring.cloud.stream.bindings.output.producer.partitionKeyExtractorClass</code> property.
|
||
Since version 3.0, this property is removed.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Once the message key is calculated, the partition selection process determines the target partition as a value between <code>0</code> and <code>partitionCount - 1</code>.
|
||
The default calculation, applicable in most scenarios, is based on the following formula: <code>key.hashCode() % partitionCount</code>.
|
||
This can be customized on the binding, either by setting a SpEL expression to be evaluated against the 'key' (through the <code>partitionSelectorExpression</code> property) or by configuring an implementation of <code>org.springframework.cloud.stream.binder.PartitionSelectorStrategy</code> as a bean (by using the @Bean annotation).
|
||
Similar to the <code>PartitionKeyExtractorStrategy</code>, you can further filter it by using the <code>spring.cloud.stream.bindings.output.producer.partitionSelectorName</code> property when more than one bean of this type is available in the Application Context, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code>--spring.cloud.stream.bindings.output.producer.partitionSelectorName=customPartitionSelector
|
||
. . .
|
||
@Bean
|
||
public CustomPartitionSelectorClass customPartitionSelector() {
|
||
return new CustomPartitionSelectorClass();
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
In previous versions of Spring Cloud Stream you could specify the implementation of <code>org.springframework.cloud.stream.binder.PartitionSelectorStrategy</code> by setting the <code>spring.cloud.stream.bindings.output.producer.partitionSelectorClass</code> property.
|
||
Since version 3.0, this property is removed.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="spring-cloud-stream-overview-configuring-input-bindings-partitioning"><a class="link" href="#spring-cloud-stream-overview-configuring-input-bindings-partitioning">Configuring Input Bindings for Partitioning</a></h4>
|
||
<div class="paragraph">
|
||
<p>An input binding (with the channel name <code>input</code>) is configured to receive partitioned data by setting its <code>partitioned</code> property, as well as the <code>instanceIndex</code> and <code>instanceCount</code> properties on the application itself, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre>spring.cloud.stream.bindings.input.consumer.partitioned=true
|
||
spring.cloud.stream.instanceIndex=3
|
||
spring.cloud.stream.instanceCount=5</pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>instanceCount</code> value represents the total number of application instances between which the data should be partitioned.
|
||
The <code>instanceIndex</code> must be a unique value across the multiple instances, with a value between <code>0</code> and <code>instanceCount - 1</code>.
|
||
The instance index helps each application instance to identify the unique partition(s) from which it receives data.
|
||
It is required by binders using technology that does not support partitioning natively.
|
||
For example, with RabbitMQ, there is a queue for each partition, with the queue name containing the instance index.
|
||
With Kafka, if <code>autoRebalanceEnabled</code> is <code>true</code> (default), Kafka takes care of distributing partitions across instances, and these properties are not required.
|
||
If <code>autoRebalanceEnabled</code> is set to false, the <code>instanceCount</code> and <code>instanceIndex</code> are used by the binder to determine which partition(s) the instance subscribes to (you must have at least as many partitions as there are instances).
|
||
The binder allocates the partitions instead of Kafka.
|
||
This might be useful if you want messages for a particular partition to always go to the same instance.
|
||
When a binder configuration requires them, it is important to set both values correctly in order to ensure that all of the data is consumed and that the application instances receive mutually exclusive datasets.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>While a scenario in which using multiple instances for partitioned data processing may be complex to set up in a standalone case, Spring Cloud Dataflow can simplify the process significantly by populating both the input and output values correctly and by letting you rely on the runtime infrastructure to provide information about the instance index and instance count.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_testing"><a class="link" href="#_testing">Testing</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides support for testing your microservice applications without connecting to a messaging system.
|
||
You can do that by using the <code>TestSupportBinder</code> provided by the <code>spring-cloud-stream-test-support</code> library, which can be added as a test dependency to the application, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"> <dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-stream-test-support</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
The <code>TestSupportBinder</code> uses the Spring Boot autoconfiguration mechanism to supersede the other binders found on the classpath.
|
||
Therefore, when adding a binder as a dependency, you must make sure that the <code>test</code> scope is being used.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The <code>TestSupportBinder</code> lets you interact with the bound channels and inspect any messages sent and received by the application.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For outbound message channels, the <code>TestSupportBinder</code> registers a single subscriber and retains the messages emitted by the application in a <code>MessageCollector</code>.
|
||
They can be retrieved during tests and have assertions made against them.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can also send messages to inbound message channels so that the consumer application can consume the messages.
|
||
The following example shows how to test both input and output channels on a processor:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
|
||
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||
public class ExampleTest {
|
||
|
||
@Autowired
|
||
private Processor processor;
|
||
|
||
@Autowired
|
||
private MessageCollector messageCollector;
|
||
|
||
@Test
|
||
@SuppressWarnings("unchecked")
|
||
public void testWiring() {
|
||
Message<String> message = new GenericMessage<>("hello");
|
||
processor.input().send(message);
|
||
Message<String> received = (Message<String>) messageCollector.forChannel(processor.output()).poll();
|
||
assertThat(received.getPayload(), equalTo("hello world"));
|
||
}
|
||
|
||
|
||
@SpringBootApplication
|
||
@EnableBinding(Processor.class)
|
||
public static class MyProcessor {
|
||
|
||
@Autowired
|
||
private Processor channels;
|
||
|
||
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
|
||
public String transform(String in) {
|
||
return in + " world";
|
||
}
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the preceding example, we create an application that has an input channel and an output channel, both bound through the <code>Processor</code> interface.
|
||
The bound interface is injected into the test so that we can have access to both channels.
|
||
We send a message on the input channel, and we use the <code>MessageCollector</code> provided by Spring Cloud Stream’s test support to capture that the message has been sent to the output channel as a result.
|
||
Once we have received the message, we can validate that the component functions correctly.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_disabling_the_test_binder_autoconfiguration"><a class="link" href="#_disabling_the_test_binder_autoconfiguration">Disabling the Test Binder Autoconfiguration</a></h3>
|
||
<div class="paragraph">
|
||
<p>The intent behind the test binder superseding all the other binders on the classpath is to make it easy to test your applications without making changes to your production dependencies.
|
||
In some cases (for example, integration tests) it is useful to use the actual production binders instead, and that requires disabling the test binder autoconfiguration.
|
||
To do so, you can exclude the <code>org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration</code> class by using one of the Spring Boot autoconfiguration exclusion mechanisms, as shown in the following example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java"> @SpringBootApplication(exclude = TestSupportBinderAutoConfiguration.class)
|
||
@EnableBinding(Processor.class)
|
||
public static class MyProcessor {
|
||
|
||
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
|
||
public String transform(String in) {
|
||
return in + " world";
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When autoconfiguration is disabled, the test binder is available on the classpath, and its <code>defaultCandidate</code> property is set to <code>false</code> so that it does not interfere with the regular user configuration. It can be referenced under the name, <code>test</code>, as shown in the following example:</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><code>spring.cloud.stream.defaultBinder=test</code></p>
|
||
</div>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="spring_integration_test_binder"><a class="link" href="#spring_integration_test_binder">Spring Integration Test Binder</a></h3>
|
||
<div class="paragraph">
|
||
<p>Current test binder was specifically designed to facilitate <em>unit testing</em> of the actual messaging components and thus bypasses some of the core functionality of the binder API.
|
||
While such light-weight approach is sufficient for a lot of cases, it usually requires additional <em>integration testing</em> with real binders (e.g., Rabbit, Kafka etc).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To begin bridging the gap between <em>unit</em> and <em>integration</em> testing we’ve developed a new test binder which uses <a href="https://spring.io/projects/spring-integration">Spring Integration</a> framework
|
||
as an in-JVM Message Broker essentially giving you the best of both worlds - a real binder without the networking.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To enable Spring Integration Test Binder all you need is:</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p>Add required dependencies</p>
|
||
</li>
|
||
<li>
|
||
<p>Remove the dependency for <code>spring-cloud-stream-test-support</code></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><strong><strong>Add required dependencies</strong></strong></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Below is the example of the required Maven POM entries which could be easily retrofitted into Gradle.</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-stream</artifactId>
|
||
<version>${spring.cloud.strea.version}</version>
|
||
<type>test-jar</type>
|
||
<scope>test</scope>
|
||
<classifier>test-binder</classifier>
|
||
</dependency>
|
||
. . .
|
||
<plugins>
|
||
<plugin>
|
||
<groupId>org.apache.maven.plugins</groupId>
|
||
<artifactId>maven-jar-plugin</artifactId>
|
||
<executions>
|
||
<execution>
|
||
<configuration>
|
||
<includes>
|
||
<include>**/integration/*</include>
|
||
</includes>
|
||
<classifier>test-binder</classifier>
|
||
</configuration>
|
||
<goals>
|
||
<goal>test-jar</goal>
|
||
</goals>
|
||
</execution>
|
||
</executions>
|
||
</plugin>
|
||
</plugins></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p><strong><strong>Remove the dependency for <code>spring-cloud-stream-test-support</code></strong></strong></p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To avoid conflicts with the existing test binder you must eremove the following entry</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml"><dependency>
|
||
<groupId>org.springframework.cloud</groupId>
|
||
<artifactId>spring-cloud-stream-test-support</artifactId>
|
||
<scope>test</scope>
|
||
</dependency></code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Now you can test your microservice as a simple unit test</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
|
||
@EnableBinding(Processor.class)
|
||
public class DemoTestBinderApplication {
|
||
|
||
public static void main(String[] args) {
|
||
SpringApplication.run(DemoTestBinderApplication.class, args);
|
||
}
|
||
|
||
@StreamListener(Processor.INPUT)
|
||
@SendTo(Processor.OUTPUT)
|
||
public String echo(String value) {
|
||
return value;
|
||
}
|
||
}
|
||
|
||
. . .
|
||
|
||
@Test
|
||
public void sampleTest() {
|
||
ApplicationContext context = new SpringApplicationBuilder(
|
||
TestChannelBinderConfiguration.class,
|
||
DemoTestBinderApplication.class)
|
||
.web(WebApplicationType.NONE).run();
|
||
InputDestination source = context.getBean(InputDestination.class);
|
||
OutputDestination target = context.getBean(OutputDestination.class);
|
||
source.send(new GenericMessage<byte[]>("hello".getBytes()));
|
||
System.out.println("Result: " + new String(target.receive().getPayload()));
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the above you simply create an ApplicationContext with your configuration (your application) while additionally supplying <code>TestChannelBinderConfiguration</code>
|
||
provided by the framework. Then you access <code>InputDestination</code> and <code>OutputDestination</code> beans to send/receive messages. In the context of this binder
|
||
<code>InputDestination</code> and <code>OutputDestination</code> emulate remote destinations such as Rabbit <em>exchange/queue</em> or Kafka <em>topic</em>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>In the future we plan to simplify the API.</p>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
In its current state Spring Integration Test Binder only supports the three bindings provided by the framework (Source, Processor, Sink) specifically to promote
|
||
light-weight microservices architectures rather then general purpose messaging applications.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
<div class="sect3">
|
||
<h4 id="_spring_integration_test_binder_and_pollablemessagesource"><a class="link" href="#_spring_integration_test_binder_and_pollablemessagesource">Spring Integration Test Binder and PollableMessageSource</a></h4>
|
||
<div class="paragraph">
|
||
<p>Spring Integration Test Binder also allows you to write tests when working with <code>PollableMessageSource</code> (see <a href="#spring-cloud-streams-overview-using-polled-consumers">Using Polled Consumers</a> for more details).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The important thing that needs to be understood though is that polling is not event-driven, and that <code>PollableMessageSource</code> is a strategy which exposes operation to produce (poll for) a Message (singular).
|
||
How often you poll or how many threads you use or where you’re polling from (message queue or file system) is entirely up to you;
|
||
In other words it is your responsibility to configure Poller or Threads or the actual source of Message. Luckily Spring has plenty of abstractions to configure exactly that.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Let’s look at the example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Test
|
||
public void samplePollingTest() {
|
||
ApplicationContext context = new SpringApplicationBuilder(SamplePolledConfiguration.class)
|
||
.web(WebApplicationType.NONE)
|
||
.run("--spring.jmx.enabled=false");
|
||
OutputDestination destination = context.getBean(OutputDestination.class);
|
||
System.out.println("Message 1: " + new String(destination.receive().getPayload()));
|
||
System.out.println("Message 2: " + new String(destination.receive().getPayload()));
|
||
System.out.println("Message 3: " + new String(destination.receive().getPayload()));
|
||
}
|
||
|
||
@EnableBinding(SamplePolledConfiguration.PolledConsumer.class)
|
||
@Import(TestChannelBinderConfiguration.class)
|
||
@EnableAutoConfiguration
|
||
public static class SamplePolledConfiguration {
|
||
@Bean
|
||
public ApplicationRunner poller(PollableMessageSource polledMessageSource, MessageChannel output, TaskExecutor taskScheduler) {
|
||
return args -> {
|
||
taskScheduler.execute(() -> {
|
||
for (int i = 0; i < 3; i++) {
|
||
try {
|
||
if (!polledMessageSource.poll(m -> {
|
||
String newPayload = ((String) m.getPayload()).toUpperCase();
|
||
output.send(new GenericMessage<>(newPayload));
|
||
})) {
|
||
Thread.sleep(2000);
|
||
}
|
||
}
|
||
catch (Exception e) {
|
||
// handle failure
|
||
}
|
||
}
|
||
});
|
||
};
|
||
}
|
||
|
||
public static interface PolledConsumer extends Source {
|
||
@Input
|
||
PollableMessageSource pollableSource();
|
||
}
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The above (very rudimentary) example will produce 3 messages in 2 second intervals sending them to the output destination of <code>Source</code>
|
||
which this binder sends to <code>OutputDestination</code> where we retrieve them (for any assertions).
|
||
Currently it prints the following:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">Message 1: POLLED DATA
|
||
Message 2: POLLED DATA
|
||
Message 3: POLLED DATA</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>As you can see the data is the same. That is because this binder defines a default implementation of the actual <code>MessageSource</code> - the source
|
||
from which the Messages are polled using <code>poll()</code> operation. While sufficient for most testing scenarios, there are cases where you may want
|
||
to define your own <code>MessageSource</code>. To do so simply configure a bean of type <code>MessageSource</code> in your test configuration providing your own
|
||
implementation of Message sourcing.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Here is the example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
|
||
public MessageSource<?> source() {
|
||
return () -> new GenericMessage<>("My Own Data " + UUID.randomUUID());
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>rendering the following output;</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-text hljs" data-lang="text">Message 1: MY OWN DATA 1C180A91-E79F-494F-ABF4-BA3F993710DA
|
||
Message 2: MY OWN DATA D8F3A477-5547-41B4-9434-E69DA7616FEE
|
||
Message 3: MY OWN DATA 20BF2E64-7FF4-4CB6-A823-4053D30B5C74</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
DO NOT name this bean <code>messageSource</code> as it is going to be in conflict with the bean of the same name (different type)
|
||
provided by Spring Boot for unrelated reasons.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_health_indicator"><a class="link" href="#_health_indicator">Health Indicator</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides a health indicator for binders.
|
||
It is registered under the name <code>binders</code> and can be enabled or disabled by setting the <code>management.health.binders.enabled</code> property.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>To enable health check you first need to enable both "web" and "actuator" by including its dependencies (see <a href="#binding_visualization_control">Binding visualization and control</a>)</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If <code>management.health.binders.enabled</code> is not set explicitly by the application, then <code>management.health.defaults.enabled</code> is matched as <code>true</code> and the binder health indicators are enabled.
|
||
If you want to disable health indicator completely, then you have to set <code>management.health.binders.enabled</code> to <code>false</code>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>You can use Spring Boot actuator health endpoint to access the health indicator - <code>/actuator/health</code>.
|
||
By default, you will only receive the top level application status when you hit the above endpoint.
|
||
In order to receive the full details from the binder specific health indicators, you need to include the property <code>management.endpoint.health.show-details</code> with the value <code>ALWAYS</code> in your application.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Health indicators are binder-specific and certain binder implementations may not necessarily provide a health indicator.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If you want to completely disable all health indicators available out of the box and instead provide your own health indicators,
|
||
you can do so by setting property <code>management.health.binders.enabled</code> to <code>false</code> and then provide your own <code>HealthIndicator</code> beans in your application.
|
||
In this case, the health indicator infrastructure from Spring Boot will still pick up these custom beans.
|
||
Even if you are not disabling the binder health indicators, you can still enhance the health checks by providing your own <code>HealthIndicator</code> beans in addition to the out of the box health checks.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When you have multiple binders in the same application, health indicators are enabled by default unless the application turns them off by setting <code>management.health.binders.enabled</code> to <code>false</code>.
|
||
In this case, if the user wants to disable health check for a subset of the binders, then that should be done by setting <code>management.health.binders.enabled</code> to <code>false</code> in the multi binder configurations’s environment.
|
||
See <a href="#multiple-systems">Connecting to Multiple Systems</a> for details on how environment specific properties can be provided.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>If there are multiple binders present in the classpath but not all of them are used in the application, this may cause some issues in the context of health indicators.
|
||
There may be implementation specific details as to how the health checks are performed. For example, a Kafka binder may decide the status as <code>DOWN</code> if there are no destinations registered by the binder.
|
||
For this reason, if you include a binder in the classpath, it is advised to use that binder by providing at least one binding (for E.g. through <code>EnableBinding</code>).
|
||
If you don’t have any bindings to provide for this binder, then that is an indication that you don’t need to include that binder in the classpath.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Lets take a concrete situation. Imagine you have both Kafka and Kafka Streams binders present in the classpath, but only use the Kafka Streams binder in the application code, i.e. only provide bindings using the Kafka Streams binder.
|
||
Since Kafka binder is not used and it has specific checks to see if any destinations are registered, the binder health heck will fail.
|
||
The top level application health check status will be reported as <code>DOWN</code>.
|
||
In this situation, you can simply remove the dependency for kafka binder from your application since you are not using it.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="spring-cloud-stream-overview-metrics-emitter"><a class="link" href="#spring-cloud-stream-overview-metrics-emitter">Metrics Emitter</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>Spring Boot Actuator provides dependency management and auto-configuration for <a href="https://micrometer.io/">Micrometer</a>, an application metrics
|
||
facade that supports numerous <a href="https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#production-ready-metrics">monitoring systems</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Spring Cloud Stream provides support for emitting any available micrometer-based metrics to a binding destination, allowing for periodic
|
||
collection of metric data from stream applications without relying on polling individual endpoints.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Metrics Emitter is activated by defining the <code>spring.cloud.stream.bindings.applicationMetrics.destination</code> property,
|
||
which specifies the name of the binding destination used by the current binder to publish metric messages.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>For example:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">spring.cloud.stream.bindings.applicationMetrics.destination=myMetricDestination</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The preceding example instructs the binder to bind to <code>myMetricDestination</code> (that is, Rabbit exchange, Kafka topic, and others).</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following properties can be used for customizing the emission of metrics:</p>
|
||
</div>
|
||
<div class="dlist">
|
||
<dl>
|
||
<dt class="hdlist1">spring.cloud.stream.metrics.key</dt>
|
||
<dd>
|
||
<p>The name of the metric being emitted. Should be a unique value per application.</p>
|
||
<div class="paragraph">
|
||
<p>Default: <code>${spring.application.name:${vcap.application.name:${spring.config.name:application}}}</code></p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.metrics.properties</dt>
|
||
<dd>
|
||
<p>Allows white listing application properties that are added to the metrics payload</p>
|
||
<div class="paragraph">
|
||
<p>Default: null.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.metrics.meter-filter</dt>
|
||
<dd>
|
||
<p>Pattern to control the 'meters' one wants to capture.
|
||
For example, specifying <code>spring.integration.*</code> captures metric information for meters whose name starts with <code>spring.integration.</code></p>
|
||
<div class="paragraph">
|
||
<p>Default: all 'meters' are captured.</p>
|
||
</div>
|
||
</dd>
|
||
<dt class="hdlist1">spring.cloud.stream.metrics.schedule-interval</dt>
|
||
<dd>
|
||
<p>Interval to control the rate of publishing metric data.</p>
|
||
<div class="paragraph">
|
||
<p>Default: 1 min</p>
|
||
</div>
|
||
</dd>
|
||
</dl>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>Consider the following:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-bash hljs" data-lang="bash">java -jar time-source.jar \
|
||
--spring.cloud.stream.bindings.applicationMetrics.destination=someMetrics \
|
||
--spring.cloud.stream.metrics.properties=spring.application** \
|
||
--spring.cloud.stream.metrics.meter-filter=spring.integration.*</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>The following example shows the payload of the data published to the binding destination as a result of the preceding command:</p>
|
||
</div>
|
||
<div class="listingblock">
|
||
<div class="content">
|
||
<pre class="highlightjs highlight"><code class="language-javascript hljs" data-lang="javascript">{
|
||
"name": "application",
|
||
"createdTime": "2018-03-23T14:48:12.700Z",
|
||
"properties": {
|
||
},
|
||
"metrics": [
|
||
{
|
||
"id": {
|
||
"name": "spring.integration.send",
|
||
"tags": [
|
||
{
|
||
"key": "exception",
|
||
"value": "none"
|
||
},
|
||
{
|
||
"key": "name",
|
||
"value": "input"
|
||
},
|
||
{
|
||
"key": "result",
|
||
"value": "success"
|
||
},
|
||
{
|
||
"key": "type",
|
||
"value": "channel"
|
||
}
|
||
],
|
||
"type": "TIMER",
|
||
"description": "Send processing time",
|
||
"baseUnit": "milliseconds"
|
||
},
|
||
"timestamp": "2018-03-23T14:48:12.697Z",
|
||
"sum": 130.340546,
|
||
"count": 6,
|
||
"mean": 21.72342433333333,
|
||
"upper": 116.176299,
|
||
"total": 130.340546
|
||
}
|
||
]
|
||
}</code></pre>
|
||
</div>
|
||
</div>
|
||
<div class="admonitionblock note">
|
||
<table>
|
||
<tr>
|
||
<td class="icon">
|
||
<i class="fa icon-note" title="Note"></i>
|
||
</td>
|
||
<td class="content">
|
||
Given that the format of the Metric message has slightly changed after migrating to Micrometer, the published message will also have
|
||
a <code>STREAM_CLOUD_STREAM_VERSION</code> header set to <code>2.x</code> to help distinguish between Metric messages from the older versions of the Spring Cloud Stream.
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_samples"><a class="link" href="#_samples">Samples</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>For Spring Cloud Stream samples, see the <a href="https://github.com/spring-cloud/spring-cloud-stream-samples">spring-cloud-stream-samples</a> repository on GitHub.</p>
|
||
</div>
|
||
<div class="sect2">
|
||
<h3 id="_deploying_stream_applications_on_cloudfoundry"><a class="link" href="#_deploying_stream_applications_on_cloudfoundry">Deploying Stream Applications on CloudFoundry</a></h3>
|
||
<div class="paragraph">
|
||
<p>On CloudFoundry, services are usually exposed through a special environment variable called <a href="https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html#VCAP-SERVICES">VCAP_SERVICES</a>.</p>
|
||
</div>
|
||
<div class="paragraph">
|
||
<p>When configuring your binder connections, you can use the values from an environment variable as explained on the <a href="http://docs.spring.io/spring-cloud-dataflow-server-cloudfoundry/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-ups">dataflow Cloud Foundry Server</a> docs.</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="sect1">
|
||
<h2 id="_binder_implementations"><a class="link" href="#_binder_implementations">Binder Implementations</a></h2>
|
||
<div class="sectionbody">
|
||
<div class="paragraph">
|
||
<p>The following is the list of available binder implementations</p>
|
||
</div>
|
||
<div class="ulist">
|
||
<ul>
|
||
<li>
|
||
<p><a href="https://cloud.spring.io/spring-cloud-stream-binder-rabbit/">RabbitMQ</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="https://cloud.spring.io/spring-cloud-stream-binder-kafka/">Apache Kafka</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="https://github.com/spring-cloud/spring-cloud-stream-binder-aws-kinesis">Amazon Kinesis</a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="https://github.com/spring-cloud/spring-cloud-gcp/tree/master/spring-cloud-gcp-pubsub-stream-binder">Google PubSub <em>(partner maintained)</em></a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="https://github.com/SolaceProducts/spring-cloud-stream-binder-solace">Solace PubSub+ <em>(partner maintained)</em></a></p>
|
||
</li>
|
||
<li>
|
||
<p><a href="https://github.com/Microsoft/spring-cloud-azure/tree/master/spring-cloud-azure-stream-binder/spring-cloud-azure-eventhubs-stream-binder">Azure Event Hubs <em>(partner maintained)</em></a></p>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<script type="text/javascript" src="js/tocbot/tocbot.min.js"></script>
|
||
<script type="text/javascript" src="js/toc.js"></script>
|
||
<link rel="stylesheet" href="js/highlight/styles/atom-one-dark-reasonable.min.css">
|
||
<script src="js/highlight/highlight.min.js"></script>
|
||
<script>hljs.initHighlighting()</script>
|
||
</body>
|
||
</html> |