Files
spring-cloud-function/reference/html/spring-cloud-function.html
2019-11-22 11:55:16 +00:00

1572 lines
73 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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.8">
<title>Spring Cloud Function</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">
<h1>Spring Cloud Function</h1>
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_introduction">Introduction</a></li>
<li><a href="#_getting_started">Getting Started</a></li>
<li><a href="#_programming_model">Programming model</a>
<ul class="sectlevel2">
<li><a href="#_function_catalog_and_flexible_function_signatures">Function Catalog and Flexible Function Signatures</a></li>
<li><a href="#_java_8_function_support">Java 8 function support</a></li>
<li><a href="#_function_composition">Function Composition</a></li>
<li><a href="#_function_routing">Function Routing</a></li>
<li><a href="#_function_arity">Function Arity</a></li>
<li><a href="#_kotlin_lambda_support">Kotlin Lambda support</a></li>
<li><a href="#_function_component_scan">Function Component Scan</a></li>
</ul>
</li>
<li><a href="#_standalone_web_applications">Standalone Web Applications</a></li>
<li><a href="#_standalone_streaming_applications">Standalone Streaming Applications</a></li>
<li><a href="#_deploying_a_packaged_function">Deploying a Packaged Function</a></li>
<li><a href="#_functional_bean_definitions">Functional Bean Definitions</a>
<ul class="sectlevel2">
<li><a href="#_comparing_functional_with_traditional_bean_definitions">Comparing Functional with Traditional Bean Definitions</a></li>
<li><a href="#_testing_functional_applications">Testing Functional Applications</a></li>
<li><a href="#_limitations_of_functional_bean_declaration">Limitations of Functional Bean Declaration</a></li>
</ul>
</li>
<li><a href="#_dynamic_compilation">Dynamic Compilation</a></li>
<li><a href="#_serverless_platform_adapters">Serverless Platform Adapters</a>
<ul class="sectlevel2">
<li><a href="#_aws_lambda">AWS Lambda</a></li>
<li><a href="#_microsoft_azure">Microsoft Azure</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Mark Fisher, Dave Syer, Oleg Zhurakousky, Anshul Mehra</p>
</div>
<div class="paragraph">
<p><strong>3.0.1.BUILD-SNAPSHOT</strong></p>
</div>
<hr>
</div>
</div>
<div class="sect1">
<h2 id="_introduction"><a class="link" href="#_introduction">Introduction</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Spring Cloud Function is a project with the following high-level goals:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Promote the implementation of business logic via functions.</p>
</li>
<li>
<p>Decouple the development lifecycle of business logic from any specific runtime target so that the same code can run as a web endpoint, a stream processor, or a task.</p>
</li>
<li>
<p>Support a uniform programming model across serverless providers, as well as the ability to run standalone (locally or in a PaaS).</p>
</li>
<li>
<p>Enable Spring Boot features (auto-configuration, dependency injection, metrics) on serverless providers.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>It abstracts away all of the transport details and
infrastructure, allowing the developer to keep all the familiar tools
and processes, and focus firmly on business logic.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s a complete, executable, testable Spring Boot application
(implementing a simple string manipulation):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
public class Application {
@Bean
public Function&lt;Flux&lt;String&gt;, Flux&lt;String&gt;&gt; uppercase() {
return flux -&gt; flux.map(value -&gt; value.toUpperCase());
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It&#8217;s just a Spring Boot application, so it can be built, run and
tested, locally and in a CI build, the same way as any other Spring
Boot application. The <code>Function</code> is from <code>java.util</code> and <code>Flux</code> is a
<a href="https://www.reactive-streams.org/">Reactive Streams</a> <code>Publisher</code> from
<a href="https://projectreactor.io/">Project Reactor</a>. The function can be
accessed over HTTP or messaging.</p>
</div>
<div class="paragraph">
<p>Spring Cloud Function has 4 main features:</p>
</div>
<div class="paragraph">
<p>In the nutshell Spring Cloud Function provides the following features:
1. Wrappers for <code>@Beans</code> of type <code>Function</code>, <code>Consumer</code> and
<code>Supplier</code>, exposing them to the outside world as either HTTP
endpoints and/or message stream listeners/publishers with RabbitMQ, Kafka etc.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><em>Choice of programming styles - reactive, imperative or hybrid.</em></p>
</li>
<li>
<p><em>Function composition and adaptation (e.g., composing imperative functions with reactive).</em></p>
</li>
<li>
<p><em>Support for reactive function with multiple inputs and outputs allowing merging, joining and other complex streaming operation to be handled by functions.</em></p>
</li>
<li>
<p><em>Transparent type conversion of inputs and outputs.</em></p>
</li>
<li>
<p><em>Packaging functions for deployments, specific to the target platform (e.g., Project Riff, AWS Lambda and more)</em></p>
</li>
<li>
<p><em>Adapters to expose function to the outside world as HTTP endpoints etc.</em></p>
</li>
<li>
<p><em>Deploying a JAR file containing such an application context with an isolated classloader, so that you can pack them together in a single JVM.</em></p>
</li>
<li>
<p><em>Compiling strings which are Java function bodies into bytecode, and then turning them into <code>@Beans</code> that can be wrapped as above.</em></p>
</li>
<li>
<p><em>Adapters for <a href="https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-adapters/spring-cloud-function-adapter-aws">AWS Lambda</a>, <a href="https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-adapters/spring-cloud-function-adapter-azure">Azure</a>, <a href="https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk">Apache OpenWhisk</a> and possibly other "serverless" service providers.</em></p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at <a href="https://github.com/spring-cloud/spring-cloud-function/tree/master/docs/src/main/asciidoc">github</a>.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_getting_started"><a class="link" href="#_getting_started">Getting Started</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Build from the command line (and "install" the samples):</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ ./mvnw clean install</pre>
</div>
</div>
<div class="paragraph">
<p>(If you like to YOLO add <code>-DskipTests</code>.)</p>
</div>
<div class="paragraph">
<p>Run one of the samples, e.g.</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ java -jar spring-cloud-function-samples/function-sample/target/*.jar</pre>
</div>
</div>
<div class="paragraph">
<p>This runs the app and exposes its functions over HTTP, so you can
convert a string to uppercase, like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d Hello
HELLO</pre>
</div>
</div>
<div class="paragraph">
<p>You can convert multiple strings (a <code>Flux&lt;String&gt;</code>) by separating them
with new lines</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ curl -H "Content-Type: text/plain" localhost:8080/uppercase -d 'Hello
&gt; World'
HELLOWORLD</pre>
</div>
</div>
<div class="paragraph">
<p>(You can use <code><sup>Q</sup>J</code> in a terminal to insert a new line in a literal
string like that.)</p>
</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="sect2">
<h3 id="_function_catalog_and_flexible_function_signatures"><a class="link" href="#_function_catalog_and_flexible_function_signatures">Function Catalog and Flexible Function Signatures</a></h3>
<div class="paragraph">
<p>One of the main features of Spring Cloud Function is to adapt and support a range of type signatures for user-defined functions,
while providing a consistent execution model.
That&#8217;s why all user defined functions are transformed into a canonical representation by <code>FunctionCatalog</code>.</p>
</div>
<div class="paragraph">
<p>While users don&#8217;t normally have to care about the <code>FunctionCatalog</code> at all, it is useful to know what
kind of functions are supported in user code.</p>
</div>
<div class="paragraph">
<p>It is also important to understand that Spring Cloud Function provides first class support for reactive API
provided by <a href="https://projectreactor.io/">Project Reactor</a> allowing reactive primitives such as <code>Mono</code> and <code>Flux</code>
to be used as types in user defined functions providing greater flexibility when choosing programming model for
your function implementation.
Reactive programming model also enables functional support for features that would be otherwise difficult to impossible to implement
using imperative programming style. For more on this please read <a href="#_function_arity">Function Arity</a> section.</p>
</div>
</div>
<div class="sect2">
<h3 id="_java_8_function_support"><a class="link" href="#_java_8_function_support">Java 8 function support</a></h3>
<div class="paragraph">
<p>Spring Cloud Function embraces and builds on top of the 3 core functional interfaces defined by Java
and available to us since Java 8.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Supplier&lt;O&gt;</p>
</li>
<li>
<p>Function&lt;I, O&gt;</p>
</li>
<li>
<p>Consumer&lt;I&gt;</p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="_supplier"><a class="link" href="#_supplier">Supplier</a></h4>
<div class="paragraph">
<p>Supplier can be <em>reactive</em> - <code>Supplier&lt;Flux&lt;T&gt;&gt;</code>
or <em>imperative</em> - <code>Supplier&lt;T&gt;</code>. From the invocation standpoint this should make no difference
to the implementor of such Supplier. However, when used within frameworks
(e.g., <a href="https://spring.io/projects/spring-cloud-stream">Spring Cloud Stream</a>), Suppliers, especially reactive,
often used to represent the source of the stream, therefore they are invoked once to get the stream (e.g., Flux)
to which consumers can subscribe to. In other words such suppliers represent an equivalent of an <em>infinite stream</em>.
However, the same reactive suppliers can also represent <em>finite</em> stream(s) (e.g., result set on the polled JDBC data).
In those cases such reactive suppliers must be hooked up to some polling mechanism of the underlying framework.</p>
</div>
<div class="paragraph">
<p>To assist with that Spring Cloud Function provides a marker annotation
<code>org.springframework.cloud.function.context.PollableSupplier</code> to signal that such supplier produces a
finite stream and may need to be polled again. That said, it is important to understand that Spring Cloud Function itself
provides no behavior for this annotation.</p>
</div>
<div class="paragraph">
<p>In addition <code>PollableSupplier</code> annotation exposes a <em>splittable</em> attribute to signal that produced stream
needs to be split (see <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/Sequencer.html">Splitter EIP</a>)</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">@PollableSupplier(splittable = true)
public Supplier&lt;Flux&lt;String&gt;&gt; someSupplier() {
return () -&gt; {
String v1 = String.valueOf(System.nanoTime());
String v2 = String.valueOf(System.nanoTime());
String v3 = String.valueOf(System.nanoTime());
return Flux.just(v1, v2, v3);
};
}</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_function"><a class="link" href="#_function">Function</a></h4>
<div class="paragraph">
<p>Function can also be written in imperative or reactive way, yet unlike Supplier and Consumer there are
no special considerations for the implementor other then understanding that when used within frameworks
such as <a href="https://spring.io/projects/spring-cloud-stream">Spring Cloud Stream</a> and others, reactive function is
invoked only once to pass a reference to the stream (Flux or Mono) and imperative is invoked once per event.</p>
</div>
</div>
<div class="sect3">
<h4 id="_consumer"><a class="link" href="#_consumer">Consumer</a></h4>
<div class="paragraph">
<p>Consumer is a little bit special because it has a <code>void</code> return type,
which implies blocking, at least potentially. Most likely you will not
need to write <code>Consumer&lt;Flux&lt;?&gt;&gt;</code>, but if you do need to do that,
remember to subscribe to the input flux. If you declare a <code>Consumer</code>
of a non publisher type (which is normal), it will be converted to a
function that returns a publisher, so that it can be subscribed to in
a controlled way.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_function_composition"><a class="link" href="#_function_composition">Function Composition</a></h3>
<div class="paragraph">
<p>Function Composition is a feature that allows one to compose several functions into one.
The core support is based on function composition feature available with <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html#andThen-java.util.function.Function-">Function.andThen(..)</a>
support available since Java 8. However on top of it, we provide few additional features.</p>
</div>
<div class="sect3">
<h4 id="_declarative_function_composition"><a class="link" href="#_declarative_function_composition">Declarative Function Composition</a></h4>
<div class="paragraph">
<p>This feature allows you to provide composition instruction in a declarative way using <code>|</code> (pipe) or <code>,</code> (comma) delimiter
when providing <code>spring.cloud.function.definition</code> property.</p>
</div>
<div class="paragraph">
<p>For example</p>
</div>
<div class="listingblock">
<div class="content">
<pre>--spring.cloud.function.definition=uppercase|reverse</pre>
</div>
</div>
<div class="paragraph">
<p>Here we effectively provided a definition of a single function which itself is a composition of
function <code>uppercase</code> and function <code>reverse</code>. In fact that is one of the reasons why the property name is <em>definition</em> and not <em>name</em>,
since the definition of a function can be a composition of several named functions.
And as mentioned you can use <code>,</code> instead of pipe (such as <code>&#8230;&#8203;definition=uppercase,reverse</code>).</p>
</div>
</div>
<div class="sect3">
<h4 id="_composing_non_functions"><a class="link" href="#_composing_non_functions">Composing non-Functions</a></h4>
<div class="paragraph">
<p>Spring Cloud Function also supports composing Supplier with <code>Consumer</code> or <code>Function</code> as well as <code>Function</code> with <code>Consumer</code>.
What&#8217;s important here is to understand the end product of such definitions.
Composing Supplier with Function still results in Supplier while composing Supplier with Consumer will effectively render Runnable.
Following the same logic composing Function with Consumer will result in Consumer.</p>
</div>
<div class="paragraph">
<p>And of course you can&#8217;t compose uncomposable such as Consumer and Function, Consumer and Supplier etc.</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_function_routing"><a class="link" href="#_function_routing">Function Routing</a></h3>
<div class="paragraph">
<p>Since version 2.2 Spring Cloud Function provides routing feature allowing
you to invoke a single function which acts as a router to an actual function you wish to invoke
This feature is very useful in certain FAAS environments where maintaining configurations
for several functions could be cumbersome or exposing more then one function is not possible.</p>
</div>
<div class="paragraph">
<p>The <code>RoutingFunction</code> is registered in <em>FunctionCatalog</em> under the name <code>functionRouter</code>. For simplicity
and consistency you can also refer to <code>RoutingFunction.FUNCTION_NAME</code> constant.</p>
</div>
<div class="paragraph">
<p>This function has the following signature:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public class RoutingFunction implements Function&lt;Object, Object&gt; {
. . .
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The routing instructions could be communicated in several ways;</p>
</div>
<div class="paragraph">
<p><strong>Message Headers</strong></p>
</div>
<div class="paragraph">
<p>If the input argument is of type <code>Message&lt;?&gt;</code>, you can communicate routing instruction by setting one of
<code>spring.cloud.function.definition</code> or <code>spring.cloud.function.routing-expression</code> Message headers.
For more static cases you can use <code>spring.cloud.function.definition</code> header which allows you to provide
the name of a single function (e.g., <code>&#8230;&#8203;definition=foo</code>) or a composition instruction (e.g., <code>&#8230;&#8203;definition=foo|bar|baz</code>).
For more dynamic cases you can use <code>spring.cloud.function.routing-expression</code> header which allows
you to use Spring Expression Language (SpEL) and provide SpEL expression that should resolve
into definition of a function (as described above).</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
SpEL evaluation context&#8217;s root object is the
actual input argument, so in he case of <code>Message&lt;?&gt;</code> you can construct expression that has access
to both <code>payload</code> and <code>headers</code> (e.g., <code>spring.cloud.function.routing-expression=headers.function_name</code>).
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>In specific execution environments/models the adapters are responsible to translate and communicate
<code>spring.cloud.function.definition</code> and/or <code>spring.cloud.function.routing-expression</code> via Message header.
For example, when using <em>spring-cloud-function-web</em> you can provide <code>spring.cloud.function.definition</code> as an HTTP
header and the framework will propagate it as well as other HTTP headers as Message headers.</p>
</div>
<div class="paragraph">
<p><strong>Application Properties</strong></p>
</div>
<div class="paragraph">
<p>Routing instruction can also be communicated via <code>spring.cloud.function.definition</code>
or <code>spring.cloud.function.routing-expression</code> as application properties. The rules described in the
previous section apply here as well. The only difference is you provide these instructions as
application properties (e.g., <code>--spring.cloud.function.definition=foo</code>).</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
When dealing with reactive inputs (e.g., Publisher), routing instructions must only be provided via Function properties. This is
due to the nature of the reactive functions which are invoked only once to pass a Publisher and the rest
is handled by the reactor, hence we can not access and/or rely on the routing instructions communicated via individual
values (e.g., Message).
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_function_arity"><a class="link" href="#_function_arity">Function Arity</a></h3>
<div class="paragraph">
<p>There are times when a stream of data needs to be categorized and organized. For example,
consider a classic big-data use case of dealing with unorganized data containing, lets say,
orders and invoices, and you want each to go into a separate data store.
This is where function arity (functions with multiple inputs and outputs) support
comes to play.</p>
</div>
<div class="paragraph">
<p>Lets look at an example of such a function (full implementation details are available
<a href="https://github.com/spring-cloud/spring-cloud-stream/blob/master/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/function/MultipleInputOutputFunctionTests.java#L342">here</a>),</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public Function&lt;Flux&lt;Integer&gt;, Tuple2&lt;Flux&lt;String&gt;, Flux&lt;String&gt;&gt;&gt; organise() {
return flux -&gt; ...;
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Given that Project Reactor is a core dependency of SCF, we are using its Tuple library.
Tuples give us a unique advantage by communicating to us both <em>cardinality</em> and <em>type</em> information.
Both are extremely important in the context of SCSt. Cardinality lets us know
how many input and output bindings need to be created and bound to the corresponding
inputs and outputs of a function. Awareness of the type information ensures proper type
conversion.</p>
</div>
<div class="paragraph">
<p>Also, this is where the index part of the naming convention for binding
names comes into play, since, in this function, the two output binding
names are <code>organise-out-0</code> and <code>organise-out-1</code>.</p>
</div>
<div class="admonitionblock important">
<table>
<tr>
<td class="icon">
<i class="fa icon-important" title="Important"></i>
</td>
<td class="content">
IMPORTANT: At the moment, function arity is <strong>only</strong> supported for reactive functions
(<code>Function&lt;TupleN&lt;Flux&lt;?&gt;&#8230;&#8203;&gt;, TupleN&lt;Flux&lt;?&gt;&#8230;&#8203;&gt;&gt;</code>) centered on Complex event processing
where evaluation and computation on confluence of events typically requires view into a
stream of events rather than single event.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_kotlin_lambda_support"><a class="link" href="#_kotlin_lambda_support">Kotlin Lambda support</a></h3>
<div class="paragraph">
<p>We also provide support for Kotlin lambdas (since v2.0).
Consider the following:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
open fun kotlinSupplier(): () -&gt; String {
return { "Hello from Kotlin" }
}
@Bean
open fun kotlinFunction(): (String) -&gt; String {
return { it.toUpperCase() }
}
@Bean
open fun kotlinConsumer(): (String) -&gt; Unit {
return { println(it) }
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The above represents Kotlin lambdas configured as Spring beans. The signature of each maps to a Java equivalent of
<code>Supplier</code>, <code>Function</code> and <code>Consumer</code>, and thus supported/recognized signatures by the framework.
While mechanics of Kotlin-to-Java mapping are outside of the scope of this documentation, it is important to understand that the
same rules for signature transformation outlined in "Java 8 function support" section are applied here as well.</p>
</div>
<div class="paragraph">
<p>To enable Kotlin support all you need is to add <code>spring-cloud-function-kotlin</code> module to your classpath which contains the appropriate
autoconfiguration and supporting classes.</p>
</div>
</div>
<div class="sect2">
<h3 id="_function_component_scan"><a class="link" href="#_function_component_scan">Function Component Scan</a></h3>
<div class="paragraph">
<p>Spring Cloud Function will scan for implementations of <code>Function</code>,
<code>Consumer</code> and <code>Supplier</code> in a package called <code>functions</code> if it
exists. Using this feature you can write functions that have no
dependencies on Spring - not even the <code>@Component</code> annotation is
needed. If you want to use a different package, you can set
<code>spring.cloud.function.scan.packages</code>. You can also use
<code>spring.cloud.function.scan.enabled=false</code> to switch off the scan
completely.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_standalone_web_applications"><a class="link" href="#_standalone_web_applications">Standalone Web Applications</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>The <code>spring-cloud-function-web</code> module has autoconfiguration that
activates when it is included in a Spring Boot web application (with
MVC support). There is also a <code>spring-cloud-starter-function-web</code> to
collect all the optional dependencies in case you just want a simple
getting started experience.</p>
</div>
<div class="paragraph">
<p>With the web configurations activated your app will have an MVC
endpoint (on "/" by default, but configurable with
<code>spring.cloud.function.web.path</code>) that can be used to access the
functions in the application context. The supported content types are
plain text and JSON.</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
<col style="width: 20%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Method</th>
<th class="tableblock halign-left valign-top">Path</th>
<th class="tableblock halign-left valign-top">Request</th>
<th class="tableblock halign-left valign-top">Response</th>
<th class="tableblock halign-left valign-top">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/{supplier}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">-</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Items from the named supplier</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">200 OK</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/{consumer}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">JSON object or text</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Mirrors input and pushes request body into consumer</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">202 Accepted</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/{consumer}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">JSON array or text with new lines</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Mirrors input and pushes body into consumer one by one</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">202 Accepted</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/{function}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">JSON object or text</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The result of applying the named function</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">200 OK</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">POST</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/{function}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">JSON array or text with new lines</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">The result of applying the named function</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">200 OK</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">GET</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">/{function}/{item}</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">-</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Convert the item into an object and return the result of applying the function</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">200 OK</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>As the table above shows the behaviour of the endpoint depends on the method and also the type of incoming request data. When the incoming data is single valued, and the target function is declared as obviously single valued (i.e. not returning a collection or <code>Flux</code>), then the response will also contain a single value.
For multi-valued responses the client can ask for a server-sent event stream by sending `Accept: text/event-stream".</p>
</div>
<div class="paragraph">
<p>If there is only a single function (consumer etc.) in the catalog, the name in the path is optional.
Composite functions can be addressed using pipes or commas to separate function names (pipes are legal in URL paths, but a bit awkward to type on the command line).</p>
</div>
<div class="paragraph">
<p>For cases where there is more then a single function in catalog and you want to map a specific function to the root
path (e.g., "/"), or you want to compose several functions and then map to the root path you can do so by providing
<code>spring.cloud.function.definition</code> property which essentially used by spring-=cloud-function-web module to provide
default mapping for cases where there is some type of a conflict (e.g., more then one function available etc).</p>
</div>
<div class="paragraph">
<p>For example,</p>
</div>
<div class="listingblock">
<div class="content">
<pre>--spring.cloud.function.definition=foo|bar</pre>
</div>
</div>
<div class="paragraph">
<p>The above property will compose 'foo' and 'bar' function and map the composed function to the "/" path.</p>
</div>
<div class="paragraph">
<p>Functions and consumers that are declared with input and output in <code>Message&lt;?&gt;</code> will see the request headers on the input messages, and the output message headers will be converted to HTTP headers.</p>
</div>
<div class="paragraph">
<p>When POSTing text the response format might be different with Spring Boot 2.0 and older versions, depending on the content negotiation (provide content type and accpt headers for the best results).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_standalone_streaming_applications"><a class="link" href="#_standalone_streaming_applications">Standalone Streaming Applications</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>To send or receive messages from a broker (such as RabbitMQ or Kafka) you can leverage <code>spring-cloud-stream</code> project and it&#8217;s integration with Spring Cloud Function.
Please refer to <a href="https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/#_spring_cloud_function">Spring Cloud Function</a> section of the Spring Cloud Stream reference manual for more details and examples.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_deploying_a_packaged_function"><a class="link" href="#_deploying_a_packaged_function">Deploying a Packaged Function</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Spring Cloud Function provides a "deployer" library that allows you to launch a jar file (or exploded archive, or set of jar files) with an isolated class loader and expose the functions defined in it. This is quite a powerful tool that would allow you to, for instance, adapt a function to a range of different input-output adapters without changing the target jar file. Serverless platforms often have this kind of feature built in, so you could see it as a building block for a function invoker in such a platform (indeed the <a href="https://projectriff.io">Riff</a> Java function invoker uses this library).</p>
</div>
<div class="paragraph">
<p>The standard entry point is to add <code>spring-cloud-function-deployer</code> to the classpath, the deployer kicks in and looks for some configuration to tell it where to find the function jar.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-function-deployer&lt;/artifactId&gt;
&lt;version&gt;${spring.cloud.function.version}&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>At a minimum the user has to provide a <code>spring.cloud.function.location</code> which is a URL or resource location for the archive containing the functions. It can optionally use a <code>maven:</code> prefix to locate the artifact via a dependency lookup (see <code>FunctionProperties</code> for complete details). A Spring Boot application is bootstrapped from the jar file, using the <code>MANIFEST.MF</code> to locate a start class, so that a standard Spring Boot fat jar works well, for example. If the target jar can be launched successfully then the result is a function registered in the main application&#8217;s <code>FunctionCatalog</code>. The registered function can be applied by code in the main application, even though it was created in an isolated class loader (by deault).</p>
</div>
<div class="paragraph">
<p>Here is the example of deploying a JAR which contains an 'uppercase' function and invoking it .</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
public class DeployFunctionDemo {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DeployFunctionDemo.class,
"--spring.cloud.function.location=..../target/uppercase-0.0.1-SNAPSHOT.jar",
"--spring.cloud.function.definition=uppercase");
FunctionCatalog catalog = context.getBean(FunctionCatalog.class);
Function&lt;String, String&gt; function = catalog.lookup("uppercase");
System.out.println(function.apply("hello"));
}
}</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_functional_bean_definitions"><a class="link" href="#_functional_bean_definitions">Functional Bean Definitions</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Spring Cloud Function supports a "functional" style of bean declarations for small apps where you need fast startup. The functional style of bean declaration was a feature of Spring Framework 5.0 with significant enhancements in 5.1.</p>
</div>
<div class="sect2">
<h3 id="_comparing_functional_with_traditional_bean_definitions"><a class="link" href="#_comparing_functional_with_traditional_bean_definitions">Comparing Functional with Traditional Bean Definitions</a></h3>
<div class="paragraph">
<p>Here&#8217;s a vanilla Spring Cloud Function application from with the
familiar <code>@Configuration</code> and <code>@Bean</code> declaration style:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootApplication
public class DemoApplication {
@Bean
public Function&lt;String, String&gt; uppercase() {
return value -&gt; value.toUpperCase();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can run the above in a serverless platform, like AWS Lambda or Azure Functions, or you can run it in its own HTTP server just by including <code>spring-cloud-function-starter-web</code> on the classpath. Running the main method would expose an endpoint that you can use to ping that <code>uppercase</code> function:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code>$ curl localhost:8080 -d foo
FOO</code></pre>
</div>
</div>
<div class="paragraph">
<p>The web adapter in <code>spring-cloud-function-starter-web</code> uses Spring MVC, so you needed a Servlet container. You can also use Webflux where the default server is netty (even though you can still use Servlet containers if you want to) - just include the <code>spring-cloud-starter-function-webflux</code> dependency instead. The functionality is the same, and the user application code can be used in both.</p>
</div>
<div class="paragraph">
<p>Now for the functional beans: the user application code can be recast into "functional"
form, like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootConfiguration
public class DemoApplication implements ApplicationContextInitializer&lt;GenericApplicationContext&gt; {
public static void main(String[] args) {
FunctionalSpringApplication.run(DemoApplication.class, args);
}
public Function&lt;String, String&gt; uppercase() {
return value -&gt; value.toUpperCase();
}
@Override
public void initialize(GenericApplicationContext context) {
context.registerBean("demo", FunctionRegistration.class,
() -&gt; new FunctionRegistration&lt;&gt;(uppercase())
.type(FunctionType.from(String.class).to(String.class)));
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The main differences are:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>The main class is an <code>ApplicationContextInitializer</code>.</p>
</li>
<li>
<p>The <code>@Bean</code> methods have been converted to calls to <code>context.registerBean()</code></p>
</li>
<li>
<p>The <code>@SpringBootApplication</code> has been replaced with
<code>@SpringBootConfiguration</code> to signify that we are not enabling Spring
Boot autoconfiguration, and yet still marking the class as an "entry
point".</p>
</li>
<li>
<p>The <code>SpringApplication</code> from Spring Boot has been replaced with a
<code>FunctionalSpringApplication</code> from Spring Cloud Function (it&#8217;s a
subclass).</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The business logic beans that you register in a Spring Cloud Function app are of type <code>FunctionRegistration</code>. This is a wrapper that contains both the function and information about the input and output types. In the <code>@Bean</code> form of the application that information can be derived reflectively, but in a functional bean registration some of it is lost unless we use a <code>FunctionRegistration</code>.</p>
</div>
<div class="paragraph">
<p>An alternative to using an <code>ApplicationContextInitializer</code> and <code>FunctionRegistration</code> is to make the application itself implement <code>Function</code> (or <code>Consumer</code> or <code>Supplier</code>). Example (equivalent to the above):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@SpringBootConfiguration
public class DemoApplication implements Function&lt;String, String&gt; {
public static void main(String[] args) {
FunctionalSpringApplication.run(DemoApplication.class, args);
}
@Override
public String uppercase(String value) {
return value.toUpperCase();
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It would also work if you add a separate, standalone class of type <code>Function</code> and register it with the <code>SpringApplication</code> using an alternative form of the <code>run()</code> method. The main thing is that the generic type information is available at runtime through the class declaration.</p>
</div>
<div class="paragraph">
<p>The app runs in its own HTTP server if you add <code>spring-cloud-starter-function-webflux</code> (it won&#8217;t work with the MVC starter at the moment because the functional form of the embedded Servlet container hasn&#8217;t been implemented). The app also runs just fine in AWS Lambda or Azure Functions, and the improvements in startup time are dramatic.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
The "lite" web server has some limitations for the range of <code>Function</code> signatures - in particular it doesn&#8217;t (yet) support <code>Message</code> input and output, but POJOs and any kind of <code>Publisher</code> should be fine.
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_testing_functional_applications"><a class="link" href="#_testing_functional_applications">Testing Functional Applications</a></h3>
<div class="paragraph">
<p>Spring Cloud Function also has some utilities for integration testing that will be very familiar to Spring Boot users. For example, here is an integration test for the HTTP server wrapping the app above:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
@FunctionalSpringBootTest
@AutoConfigureWebTestClient
public class FunctionalTests {
@Autowired
private WebTestClient client;
@Test
public void words() throws Exception {
client.post().uri("/").body(Mono.just("foo"), String.class).exchange()
.expectStatus().isOk().expectBody(String.class).isEqualTo("FOO");
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This test is almost identical to the one you would write for the <code>@Bean</code> version of the same app - the only difference is the <code>@FunctionalSpringBootTest</code> annotation, instead of the regular <code>@SpringBootTest</code>. All the other pieces, like the <code>@Autowired</code> <code>WebTestClient</code>, are standard Spring Boot features.</p>
</div>
<div class="paragraph">
<p>Or you could write a test for a non-HTTP app using just the <code>FunctionCatalog</code>. For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@RunWith(SpringRunner.class)
@FunctionalSpringBootTest
public class FunctionalTests {
@Autowired
private FunctionCatalog catalog;
@Test
public void words() throws Exception {
Function&lt;Flux&lt;String&gt;, Flux&lt;String&gt;&gt; function = catalog.lookup(Function.class,
"function");
assertThat(function.apply(Flux.just("foo")).blockFirst()).isEqualTo("FOO");
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>(The <code>FunctionCatalog</code> always returns functions from <code>Flux</code> to <code>Flux</code>, even if the user declares them with a simpler signature.)</p>
</div>
</div>
<div class="sect2">
<h3 id="_limitations_of_functional_bean_declaration"><a class="link" href="#_limitations_of_functional_bean_declaration">Limitations of Functional Bean Declaration</a></h3>
<div class="paragraph">
<p>Most Spring Cloud Function apps have a relatively small scope compared to the whole of Spring Boot, so we are able to adapt it to these functional bean definitions easily. If you step outside that limited scope, you can extend your Spring Cloud Function app by switching back to <code>@Bean</code> style configuration, or by using a hybrid approach. If you want to take advantage of Spring Boot autoconfiguration for integrations with external datastores, for example, you will need to use <code>@EnableAutoConfiguration</code>. Your functions can still be defined using the functional declarations if you want (i.e. the "hybrid" style), but in that case you will need to explicitly switch off the "full functional mode" using <code>spring.functional.enabled=false</code> so that Spring Boot can take back control.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_dynamic_compilation"><a class="link" href="#_dynamic_compilation">Dynamic Compilation</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>There is a sample app that uses the function compiler to create a
function from a configuration property. The vanilla "function-sample"
also has that feature. And there are some scripts that you can run to
see the compilation happening at run time. To run these examples,
change into the <code>scripts</code> directory:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>cd scripts</pre>
</div>
</div>
<div class="paragraph">
<p>Also, start a RabbitMQ server locally (e.g. execute <code>rabbitmq-server</code>).</p>
</div>
<div class="paragraph">
<p>Start the Function Registry Service:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./function-registry.sh</pre>
</div>
</div>
<div class="paragraph">
<p>Register a Function:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./registerFunction.sh -n uppercase -f "f-&gt;f.map(s-&gt;s.toString().toUpperCase())"</pre>
</div>
</div>
<div class="paragraph">
<p>Run a REST Microservice using that Function:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./web.sh -f uppercase -p 9000
curl -H "Content-Type: text/plain" -H "Accept: text/plain" localhost:9000/uppercase -d foo</pre>
</div>
</div>
<div class="paragraph">
<p>Register a Supplier:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./registerSupplier.sh -n words -f "()-&gt;Flux.just(\"foo\",\"bar\")"</pre>
</div>
</div>
<div class="paragraph">
<p>Run a REST Microservice using that Supplier:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./web.sh -s words -p 9001
curl -H "Accept: application/json" localhost:9001/words</pre>
</div>
</div>
<div class="paragraph">
<p>Register a Consumer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./registerConsumer.sh -n print -t String -f "System.out::println"</pre>
</div>
</div>
<div class="paragraph">
<p>Run a REST Microservice using that Consumer:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./web.sh -c print -p 9002
curl -X POST -H "Content-Type: text/plain" -d foo localhost:9002/print</pre>
</div>
</div>
<div class="paragraph">
<p>Run Stream Processing Microservices:</p>
</div>
<div class="paragraph">
<p>First register a streaming words supplier:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./registerSupplier.sh -n wordstream -f "()-&gt;Flux.interval(Duration.ofMillis(1000)).map(i-&gt;\"message-\"+i)"</pre>
</div>
</div>
<div class="paragraph">
<p>Then start the source (supplier), processor (function), and sink (consumer) apps
(in reverse order):</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./stream.sh -p 9103 -i uppercaseWords -c print
./stream.sh -p 9102 -i words -f uppercase -o uppercaseWords
./stream.sh -p 9101 -s wordstream -o words</pre>
</div>
</div>
<div class="paragraph">
<p>The output will appear in the console of the sink app (one message per second, converted to uppercase):</p>
</div>
<div class="listingblock">
<div class="content">
<pre>MESSAGE-0
MESSAGE-1
MESSAGE-2
MESSAGE-3
MESSAGE-4
MESSAGE-5
MESSAGE-6
MESSAGE-7
MESSAGE-8
MESSAGE-9
...</pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_serverless_platform_adapters"><a class="link" href="#_serverless_platform_adapters">Serverless Platform Adapters</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>As well as being able to run as a standalone process, a Spring Cloud
Function application can be adapted to run one of the existing
serverless platforms. In the project there are adapters for
<a href="https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-adapters/spring-cloud-function-adapter-aws">AWS
Lambda</a>,
<a href="https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-adapters/spring-cloud-function-adapter-azure">Azure</a>,
and
<a href="https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-adapters/spring-cloud-function-adapter-openwhisk">Apache
OpenWhisk</a>. The <a href="https://github.com/fnproject/fn">Oracle Fn platform</a>
has its own Spring Cloud Function adapter. And
<a href="https://projectriff.io">Riff</a> supports Java functions and its
<a href="https://github.com/projectriff/java-function-invoker">Java Function
Invoker</a> acts natively is an adapter for Spring Cloud Function jars.</p>
</div>
<div class="sect2">
<h3 id="_aws_lambda"><a class="link" href="#_aws_lambda">AWS Lambda</a></h3>
<div class="paragraph">
<p>The <a href="https://aws.amazon.com/">AWS</a> adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda.</p>
</div>
<div class="paragraph">
<p>The adapter has a couple of generic request handlers that you can use. The most generic is <code>SpringBootStreamHandler</code>, which uses a Jackson <code>ObjectMapper</code> provided by Spring Boot to serialize and deserialize the objects in the function. There is also a <code>SpringBootRequestHandler</code> which you can extend, and provide the input and output types as type parameters (enabling AWS to inspect the class and do the JSON conversions itself).</p>
</div>
<div class="paragraph">
<p>If your app has more than one <code>@Bean</code> of type <code>Function</code> etc. then you can choose the one to use by configuring <code>function.name</code> (e.g. as <code>FUNCTION_NAME</code> environment variable in AWS). The functions are extracted from the Spring Cloud <code>FunctionCatalog</code> (searching first for <code>Function</code> then <code>Consumer</code> and finally <code>Supplier</code>).</p>
</div>
<div class="sect3">
<h4 id="_notes_on_jar_layout"><a class="link" href="#_notes_on_jar_layout">Notes on JAR Layout</a></h4>
<div class="paragraph">
<p>You don&#8217;t need the Spring Cloud Function Web or Stream adapter at runtime in Lambda, so you might
need to exclude those before you create the JAR you send to AWS. A Lambda application has to be
shaded, but a Spring Boot standalone application does not, so you can run the same app using 2
separate jars (as per the sample). The sample app creates 2 jar files, one with an <code>aws</code>
classifier for deploying in Lambda, and one <a id="thin-jar"></a> executable (thin) jar that includes <code>spring-cloud-function-web</code>
at runtime. Spring Cloud Function will try and locate a "main class" for you from the JAR file
manifest, using the <code>Start-Class</code> attribute (which will be added for you by the Spring Boot
tooling if you use the starter parent). If there is no <code>Start-Class</code> in your manifest you can
use an environment variable or system property <code>MAIN_CLASS</code> when you deploy the function to AWS.</p>
</div>
<div class="paragraph">
<p>If you are not using the functional bean definitions but relying on Spring Boot&#8217;s auto-configuration,
then additional transformers must be configured as part of the maven-shade-plugin execution.</p>
</div>
<div id="shade-plugin-setup" class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;configuration&gt;
&lt;createDependencyReducedPom&gt;false&lt;/createDependencyReducedPom&gt;
&lt;shadedArtifactAttached&gt;true&lt;/shadedArtifactAttached&gt;
&lt;shadedClassifierName&gt;aws&lt;/shadedClassifierName&gt;
&lt;transformers&gt;
&lt;transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"&gt;
&lt;resource&gt;META-INF/spring.handlers&lt;/resource&gt;
&lt;/transformer&gt;
&lt;transformer implementation="org.springframework.boot.maven.PropertiesMergingResourceTransformer"&gt;
&lt;resource&gt;META-INF/spring.factories&lt;/resource&gt;
&lt;/transformer&gt;
&lt;transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"&gt;
&lt;resource&gt;META-INF/spring.schemas&lt;/resource&gt;
&lt;/transformer&gt;
&lt;/transformers&gt;
&lt;/configuration&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_build_file_setup"><a class="link" href="#_build_file_setup">Build file setup</a></h4>
<div class="paragraph">
<p>In order to run Spring Cloud Function applications on AWS Lambda, you can leverage Maven or Gradle
plugins offered by the cloud platform provider.</p>
</div>
<div class="sect4">
<h5 id="_maven"><a class="link" href="#_maven">Maven</a></h5>
<div class="paragraph">
<p>In order to use the adapter plugin for Maven, add the plugin dependency to your <code>pom.xml</code>
file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-function-adapter-aws&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>As pointed out in the <a href="#_notes_on_jar_layout">Notes on JAR Layout</a>, you wil need a shaded jar in order to upload it
to AWS Lambda. You can use the <a href="https://maven.apache.org/plugins/maven-shade-plugin/">Maven Shade Plugin</a> for that.
The example of the <a href="#shade-plugin-setup">setup</a> can be found above.</p>
</div>
<div class="paragraph">
<p>You can use theSpring Boot Maven Plugin to generate the <a href="#thin-jar">thin jar</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot.experimental&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-thin-layout&lt;/artifactId&gt;
&lt;version&gt;${wrapper.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can find the entire sample <code>pom.xml</code> file for deploying Spring Cloud Function
applications to AWS Lambda with Maven <a href="https://github.com/spring-cloud/spring-cloud-function/blob/master/spring-cloud-function-samples/function-sample-aws/pom.xml">here</a>.</p>
</div>
</div>
<div class="sect4">
<h5 id="_gradle"><a class="link" href="#_gradle">Gradle</a></h5>
<div class="paragraph">
<p>In order to use the adapter plugin for Gradle, add the dependency to your <code>build.gradle</code> file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">dependencies {
compile("org.springframework.cloud:spring-cloud-function-adapter-aws:${version}")
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>As pointed out in <a href="#_notes_on_jar_layout">Notes on JAR Layout</a>, you wil need a shaded jar in order to upload it
to AWS Lambda. You can use the <a href="https://plugins.gradle.org/plugin/com.github.johnrengelman.shadow/">Gradle Shadow Plugin</a> for that:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">buildscript {
dependencies {
classpath "com.github.jengelman.gradle.plugins:shadow:${shadowPluginVersion}"
}
}
apply plugin: 'com.github.johnrengelman.shadow'
assemble.dependsOn = [shadowJar]
import com.github.jengelman.gradle.plugins.shadow.transformers.*
shadowJar {
classifier = 'aws'
dependencies {
exclude(
dependency("org.springframework.cloud:spring-cloud-function-web:${springCloudFunctionVersion}"))
}
// Required for Spring
mergeServiceFiles()
append 'META-INF/spring.handlers'
append 'META-INF/spring.schemas'
append 'META-INF/spring.tooling'
transform(PropertiesFileTransformer) {
paths = ['META-INF/spring.factories']
mergeStrategy = "append"
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can use the Spring Boot Gradle Plugin and Spring Boot Thin Gradle Plugin to generate
the <a href="#thin-jar">thin jar</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-groovy hljs" data-lang="groovy">buildscript {
dependencies {
classpath("org.springframework.boot.experimental:spring-boot-thin-gradle-plugin:${wrapperVersion}")
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'org.springframework.boot'
apply plugin: 'org.springframework.boot.experimental.thin-launcher'
assemble.dependsOn = [thinJar]</code></pre>
</div>
</div>
<div class="paragraph">
<p>You can find the entire sample <code>build.gradle</code> file for deploying Spring Cloud Function
applications to AWS Lambda with Gradle <a href="https://github.com/spring-cloud/spring-cloud-function/blob/master/spring-cloud-function-samples/function-sample-aws/build.gradle">here</a>.</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_upload"><a class="link" href="#_upload">Upload</a></h4>
<div class="paragraph">
<p>Build the sample under <code>spring-cloud-function-samples/function-sample-aws</code> and upload the <code>-aws</code> jar file to Lambda. The handler can be <code>example.Handler</code> or <code>org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler</code> (FQN of the class, <em>not</em> a method reference, although Lambda does accept method references).</p>
</div>
<div class="listingblock">
<div class="content">
<pre>./mvnw -U clean package</pre>
</div>
</div>
<div class="paragraph">
<p>Using the AWS command line tools it looks like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>aws lambda create-function --function-name Uppercase --role arn:aws:iam::[USERID]:role/service-role/[ROLE] --zip-file fileb://function-sample-aws/target/function-sample-aws-2.0.0.BUILD-SNAPSHOT-aws.jar --handler org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler --description "Spring Cloud Function Adapter Example" --runtime java8 --region us-east-1 --timeout 30 --memory-size 1024 --publish</pre>
</div>
</div>
<div class="paragraph">
<p>The input type for the function in the AWS sample is a Foo with a single property called "value". So you would need this to test it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>{
"value": "test"
}</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 AWS sample app is written in the "functional" style (as an <code>ApplicationContextInitializer</code>). This is much faster on startup in Lambda than the traditional <code>@Bean</code> style, so if you don&#8217;t need <code>@Beans</code> (or <code>@EnableAutoConfiguration</code>) it&#8217;s a good choice. Warm starts are not affected.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_type_conversion"><a class="link" href="#_type_conversion">Type Conversion</a></h4>
<div class="paragraph">
<p>Spring Cloud Function will attempt to transparently handle type conversion between the raw
input stream and types declared by your function.</p>
</div>
<div class="paragraph">
<p>For example, if your function signature is as such <code>Function&lt;Foo, Bar&gt;</code> we will attempt to convert
incoming stream event to an instance of <code>Foo</code>.</p>
</div>
<div class="paragraph">
<p>In the event type is not known or can not be determined (e.g., <code>Function&lt;?, ?&gt;</code>) we will attempt to
convert an incoming stream event to a generic <code>Map</code>.</p>
</div>
<div class="sect5">
<h6 id="_raw_input"><a class="link" href="#_raw_input">Raw Input</a></h6>
<div class="paragraph">
<p>There are times when you may want to have access to a raw input. In this case all you need is to declare your
function signature to accept <code>InputStream</code>. For example, <code>Function&lt;InputStream, ?&gt;</code>. In this case
we will not attempt any conversion and will pass the raw input directly to a function.</p>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_microsoft_azure"><a class="link" href="#_microsoft_azure">Microsoft Azure</a></h3>
<div class="paragraph">
<p>The <a href="https://azure.microsoft.com">Azure</a> adapter bootstraps a Spring Cloud Function context and channels function calls from the Azure framework into the user functions, using Spring Boot configuration where necessary. Azure Functions has quite a unique, but invasive programming model, involving annotations in user code that are specific to the platform. The easiest way to use it with Spring Cloud is to extend a base class and write a method in it with the <code>@FunctionName</code> annotation which delegates to a base class method.</p>
</div>
<div class="paragraph">
<p>This project provides an adapter layer for a Spring Cloud Function application onto Azure.
You can write an app with a single <code>@Bean</code> of type <code>Function</code> and it will be deployable in Azure if you get the JAR file laid out right.</p>
</div>
<div class="paragraph">
<p>There is an <code>AzureSpringBootRequestHandler</code> which you must extend, and provide the input and output types as annotated method parameters (enabling Azure to inspect the class and create JSON bindings). The base class has two useful methods (<code>handleRequest</code> and <code>handleOutput</code>) to which you can delegate the actual function call, so mostly the function will only ever have one line.</p>
</div>
<div class="paragraph">
<p>Example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">public class FooHandler extends AzureSpringBootRequestHandler&lt;Foo, Bar&gt; {
@FunctionName("uppercase")
public Bar execute(
@HttpTrigger(name = "req", methods = { HttpMethod.GET,
HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS)
Foo foo,
ExecutionContext context) {
return handleRequest(foo, context);
}
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>This Azure handler will delegate to a <code>Function&lt;Foo,Bar&gt;</code> bean (or a <code>Function&lt;Publisher&lt;Foo&gt;,Publisher&lt;Bar&gt;&gt;</code>). Some Azure triggers (e.g. <code>@CosmosDBTrigger</code>) result in a input type of <code>List</code> and in that case you can bind to <code>List</code> in the Azure handler, or <code>String</code> (the raw JSON). The <code>List</code> input delegates to a <code>Function</code> with input type <code>Map&lt;String,Object&gt;</code>, or <code>Publisher</code> or <code>List</code> of the same type. The output of the <code>Function</code> can be a <code>List</code> (one-for-one) or a single value (aggregation), and the output binding in the Azure declaration should match.</p>
</div>
<div class="paragraph">
<p>If your app has more than one <code>@Bean</code> of type <code>Function</code> etc. then you can choose the one to use by configuring <code>function.name</code>. Or if you make the <code>@FunctionName</code> in the Azure handler method match the function name it should work that way (also for function apps with multiple functions). The functions are extracted from the Spring Cloud <code>FunctionCatalog</code> so the default function names are the same as the bean names.</p>
</div>
<div class="sect3">
<h4 id="_accessing_azure_executioncontext"><a class="link" href="#_accessing_azure_executioncontext">Accessing Azure ExecutionContext</a></h4>
<div class="paragraph">
<p>Some time there is a need to access the target execution context provided by Azure runtime in the form of <code>com.microsoft.azure.functions.ExecutionContext</code>.
For example one of such needs is logging, so it can appear in the Azure console.</p>
</div>
<div class="paragraph">
<p>For that purpose Spring Cloud Function will register <code>ExecutionContext</code> as bean in the Application context, so it could be injected into your function.
For example</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-java hljs" data-lang="java">@Bean
public Function&lt;Foo, Bar&gt; uppercase(ExecutionContext targetContext) {
return foo -&gt; {
targetContext.getLogger().info("Invoking 'uppercase' on " + foo.getValue());
return new Bar(foo.getValue().toUpperCase());
};
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>Normally type-based injection should suffice, however if need to you can also utilise the bean name under which it is registered which is <code>targetExecutionContext</code>.</p>
</div>
</div>
<div class="sect3">
<h4 id="_notes_on_jar_layout_2"><a class="link" href="#_notes_on_jar_layout_2">Notes on JAR Layout</a></h4>
<div class="paragraph">
<p>You don&#8217;t need the Spring Cloud Function Web at runtime in Azure, so you can exclude this
before you create the JAR you deploy to Azure, but it won&#8217;t be used if you include it, so
it doesn&#8217;t hurt to leave it in. A function application on Azure is an archive generated by
the Maven plugin. The function lives in the JAR file generated by this project.
The sample creates it as an executable jar, using the thin layout, so that Azure can find
the handler classes. If you prefer you can just use a regular flat JAR file.
The dependencies should <strong>not</strong> be included.</p>
</div>
</div>
<div class="sect3">
<h4 id="_build_file_setup_2"><a class="link" href="#_build_file_setup_2">Build file setup</a></h4>
<div class="paragraph">
<p>In order to run Spring Cloud Function applications on Microsoft Azure, you can leverage the Maven
plugin offered by the cloud platform provider.</p>
</div>
<div class="paragraph">
<p>In order to use the adapter plugin for Maven, add the plugin dependency to your <code>pom.xml</code>
file:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
&lt;artifactId&gt;spring-cloud-function-adapter-azure&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Then, configure the plugin. You will need to provide Azure-specific configuration for your
application, specifying the <code>resourceGroup</code>, <code>appName</code> and other optional properties, and
add the <code>package</code> goal execution so that the <code>function.json</code> file required by Azure is
generated for you. Full plugin documentation can be found in the <a href="https://github.com/microsoft/azure-maven-plugins">plugin repository</a>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-xml hljs" data-lang="xml">&lt;plugin&gt;
&lt;groupId&gt;com.microsoft.azure&lt;/groupId&gt;
&lt;artifactId&gt;azure-functions-maven-plugin&lt;/artifactId&gt;
&lt;configuration&gt;
&lt;resourceGroup&gt;${functionResourceGroup}&lt;/resourceGroup&gt;
&lt;appName&gt;${functionAppName}&lt;/appName&gt;
&lt;/configuration&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;id&gt;package-functions&lt;/id&gt;
&lt;goals&gt;
&lt;goal&gt;package&lt;/goal&gt;
&lt;/goals&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>You will also have to ensure that the files to be scanned by the plugin can be found in the
Azure functions staging directory (see the <a href="https://github.com/microsoft/azure-maven-plugins">plugin repository</a>
for more details on the staging directory and it&#8217;s default location).</p>
</div>
<div class="paragraph">
<p>You can find the entire sample <code>pom.xml</code> file for deploying Spring Cloud Function
applications to Microsoft Azure with Maven <a href="https://github.com/spring-cloud/spring-cloud-function/blob/master/spring-cloud-function-samples/function-sample-azure/pom.xml">here</a>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
As of yet, only Maven plugin is available. Gradle plugin has not been created by
the cloud platform provider.
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_build"><a class="link" href="#_build">Build</a></h4>
<div class="listingblock">
<div class="content">
<pre>./mvnw -U clean package</pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_running_the_sample"><a class="link" href="#_running_the_sample">Running the sample</a></h4>
<div class="paragraph">
<p>You can run the sample locally, just like the other Spring Cloud Function samples:</p>
</div>
<hr>
<hr>
<div class="paragraph">
<p>and <code>curl -H "Content-Type: text/plain" localhost:8080/function -d '{"value": "hello foobar"}'</code>.</p>
</div>
<div class="paragraph">
<p>You will need the <code>az</code> CLI app (see <a href="https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven" class="bare">https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first-java-maven</a> for more detail). To deploy the function on Azure runtime:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>$ az login
$ mvn azure-functions:deploy</pre>
</div>
</div>
<div class="paragraph">
<p>On another terminal try this: <code>curl <a href="https://&lt;azure-function-url-from-the-log&gt;/api/uppercase" class="bare">https://&lt;azure-function-url-from-the-log&gt;/api/uppercase</a> -d '{"value": "hello foobar!"}'</code>. Please ensure that you use the right URL for the function above. Alternatively you can test the function in the Azure Dashboard UI (click on the function name, go to the right hand side and click "Test" and to the bottom right, "Run").</p>
</div>
<div class="paragraph">
<p>The input type for the function in the Azure sample is a Foo with a single property called "value". So you need this to test it with something like below:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>{
"value": "foobar"
}</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 Azure sample app is written in the "non-functional" style (using <code>@Bean</code>). The functional style (with just <code>Function</code> or <code>ApplicationContextInitializer</code>) is much faster on startup in Azure than the traditional <code>@Bean</code> style, so if you don&#8217;t need <code>@Beans</code> (or <code>@EnableAutoConfiguration</code>) it&#8217;s a good choice. Warm starts are not affected.
</td>
</tr>
</table>
</div>
</div>
</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>