Files
spring-cloud-function/spring-cloud-function.html
2019-03-19 07:57:19 +00:00

910 lines
41 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>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.selected {
background-color: #7a2519;
color: #ffffff;
}
</style>
<script src="http://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="#_building_and_running_a_function">Building and Running a Function</a></li>
<li><a href="#_function_catalog_and_flexible_function_signatures">Function Catalog and Flexible Function Signatures</a>
<ul class="sectlevel2">
<li><a href="#_java_8_function_support">Java 8 function support</a></li>
<li><a href="#_kotlin_lambda_support">Kotlin Lambda support</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></li>
</ul>
</div>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Mark Fisher, Dave Syer, Oleg Zhurakousky</p>
</div>
<div class="paragraph">
<p><strong>2.1.0.BUILD-SNAPSHOT</strong></p>
</div>
<div id="index-link" class="paragraph">
<p><a href="http://cloud.spring.io/spring-cloud-function/home.html" class="bare">http://cloud.spring.io/spring-cloud-function/home.html</a></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="http://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="olist arabic">
<ol class="arabic">
<li>
<p>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>
</li>
<li>
<p>Compiling strings which are Java function bodies into bytecode, and
then turning them into <code>@Beans</code> that can be wrapped as above.</p>
</li>
<li>
<p>Deploying a JAR file containing such an application context with an
isolated classloader, so that you can pack them together in a single
JVM.</p>
</li>
<li>
<p>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.</p>
</li>
</ol>
</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="_building_and_running_a_function"><a class="link" href="#_building_and_running_a_function">Building and Running a Function</a></h2>
<div class="sectionbody">
<div class="paragraph">
<p>The sample <code>@SpringBootApplication</code> above has a function that can be
decorated at runtime by Spring Cloud Function to be an HTTP endpoint,
or a Stream processor, for instance with RabbitMQ, Apache Kafka or
JMS.</p>
</div>
<div class="paragraph">
<p>The <code>@Beans</code> can be <code>Function</code>, <code>Consumer</code> or <code>Supplier</code> (all from
<code>java.util</code>), and their parametric types can be String or POJO.</p>
</div>
<div class="paragraph">
<p>Functions can also be of <code>Flux&lt;String&gt;</code> or <code>Flux&lt;Pojo&gt;</code> and Spring
Cloud Function takes care of converting the data to and from the
desired types, as long as it comes in as plain text or (in the case of
the POJO) JSON. There is also support for <code>Message&lt;Pojo&gt;</code> where the
message headers are copied from the incoming event, depending on the
adapter. The web adapter also supports conversion from form-encoded
data to a <code>Map</code>, and if you are using the function with Spring Cloud
Stream then all the conversion and coercion features for message
payloads will be applicable as well.</p>
</div>
<div class="paragraph">
<p>Functions can be grouped together in a single application, or deployed
one-per-jar. It&#8217;s up to the developer to choose. An app with multiple
functions can be deployed multiple times in different "personalities",
exposing different functions over different physical transports.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_function_catalog_and_flexible_function_signatures"><a class="link" href="#_function_catalog_and_flexible_function_signatures">Function Catalog and Flexible Function Signatures</a></h2>
<div class="sectionbody">
<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>, using primitives
defined by the <a href="https://projectreactor.io/">Project Reactor</a> (i.e., <code>Flux&lt;T&gt;</code> and <code>Mono&lt;T&gt;</code>).
Users can supply a bean of type <code>Function&lt;String,String&gt;</code>, for instance, and the <code>FunctionCatalog</code> will wrap it into a
<code>Function&lt;Flux&lt;String&gt;,Flux&lt;String&gt;&gt;</code>.</p>
</div>
<div class="paragraph">
<p>Using Reactor based primitives not only helps with the canonical representation of user defined functions, but it also
facilitates a more robust and flexible(reactive) execution model.</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="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>Generally speaking users can expect that if they write a function for
a plain old Java type (or primitive wrapper), then the function
catalog will wrap it to a <code>Flux</code> of the same type. If the user writes
a function using <code>Message</code> (from spring-messaging) it will receive and
transmit headers from any adapter that supports key-value metadata
(e.g. HTTP headers). Here are the details.</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">User Function</th>
<th class="tableblock halign-left valign-top">Catalog Registration</th>
<th class="tableblock halign-left valign-top"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;S,T&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;Flux&lt;S&gt;, Flux&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;Message&lt;S&gt;,Message&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;Flux&lt;Message&lt;S&gt;&gt;, Flux&lt;Message&lt;T&gt;&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;Flux&lt;S&gt;, Flux&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;Flux&lt;S&gt;, Flux&lt;T&gt;&gt;</code> (pass through)</p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Supplier&lt;T&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Supplier&lt;Flux&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Supplier&lt;Flux&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Supplier&lt;Flux&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Consumer&lt;T&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;Flux&lt;T&gt;, Mono&lt;Void&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Consumer&lt;Message&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Function&lt;Flux&lt;Message&lt;T&gt;&gt;, Mono&lt;Void&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Consumer&lt;Flux&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock"><code>Consumer&lt;Flux&lt;T&gt;&gt;</code></p></td>
<td class="tableblock halign-left valign-top"></td>
</tr>
</tbody>
</table>
<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 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>
</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 of the API is the Spring configuration annotation <code>@EnableFunctionDeployer</code>. If that is used in a Spring Boot application the deployer kicks in and looks for some configuration to tell it where to find the function jar. At a minimum the user has to provide a <code>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>
</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>
</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>