GH-530, GH-630 Improvements to AWS Custom Runtime
This commit provides initial set of improvements to executing functions in AWS Custom Runtime - Consistent invocation model for functional as well as @Bean configuration models via new CustomRuntimeEventLoop as well as AWSLambdaUtils - Clean up classpath to decrease the size of the JAR/ZIP file - Configuration simplification which no longer requires enabling of function exporter It also allows user to define functions that rely on AWS types such as APIGatewayProxyRequestEvent The existing invocation model remains in tact for the time being. Both invocation models are mutually exclusing in theit setup to avoid potential conflict. Resolves #538 Resolves #630
This commit is contained in:
@@ -57,10 +57,32 @@ For example, to deploy behind an API Gateway, use `--handler org.springframework
|
||||
|
||||
== Custom Runtime
|
||||
|
||||
An https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html[AWS Lambda custom runtime] can be created really easily using the HTTP export features in Spring Cloud Function Web. To make this work just add Spring Cloud Function AWS and Spring Cloud Function Web as dependencies in your project and set the following in your `application.properties`:
|
||||
You can also benefit from https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html[AWS Lambda custom runtime] feature of AWS Lambda
|
||||
and Spring Cloud Function provides all the necessary components to make it easy.
|
||||
|
||||
```
|
||||
spring.cloud.function.web.export.enabled=true
|
||||
```
|
||||
From the code perspective the application should look no different then any other Spring Cloud Function application.
|
||||
The only thing you need to do is to provide a `bootstrap` script in the root of your zip/jar that runs the Spring Boot application.
|
||||
and select "Custom Runtime" when creating a function in AWS.
|
||||
Here is an example 'bootstrap' file:
|
||||
```text
|
||||
#!/bin/sh
|
||||
|
||||
Set the handler name in AWS to the name of your function. Then provide a `bootstrap` script in the root of your zip/jar that runs the Spring Boot application. The functional bean definition style works for custom runtimes too, and is faster than the `@Bean` style, so the example `FuncApplication` above would work. A custom runtime can start up much quicker even than a functional bean implementation of a Java lambda - it depends mostly on the number of classes you need to load at runtime. Spring doesn't do very much here, so you can reduce the cold start time by only using primitive types in your function, for instance, and not doing any work in custom `@PostConstruct` initializers.
|
||||
cd ${LAMBDA_TASK_ROOT:-.}
|
||||
|
||||
java -Dspring.main.web-application-type=none -Dspring.jmx.enabled=false \
|
||||
-noverify -XX:TieredStopAtLevel=1 -Xss256K -XX:MaxMetaspaceSize=128M \
|
||||
-Djava.security.egd=file:/dev/./urandom \
|
||||
-cp .:`echo lib/*.jar | tr ' ' :` com.example.LambdaApplication
|
||||
```
|
||||
The `com.example.LambdaApplication` represents your application which contains function beans.
|
||||
|
||||
Set the handler name in AWS to the name of your function. You can use function composition here as well (e.g., `uppecrase|reverse`).
|
||||
That is pretty much all. Once you upload your zip/jar to AWS your function will run in custom runtime.
|
||||
We provide a https://github.com/spring-cloud/spring-cloud-function/tree/master/spring-cloud-function-samples/function-sample-aws-custom-new[sample project]
|
||||
where you can also see how to configure yoru POM to properly generate the zip file.
|
||||
|
||||
The functional bean definition style works for custom runtimes as well, and is
|
||||
faster than the `@Bean` style. A custom runtime can start up much quicker even than a functional bean implementation
|
||||
of a Java lambda - it depends mostly on the number of classes you need to load at runtime.
|
||||
Spring doesn't do very much here, so you can reduce the cold start time by only using primitive types in your function, for instance,
|
||||
and not doing any work in custom `@PostConstruct` initializers.
|
||||
|
||||
@@ -42,12 +42,6 @@
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<!-- aws sdk depends on this transitively anyway, so this is here just
|
||||
as a reminder that we need it -->
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
@@ -93,10 +87,6 @@
|
||||
</exclusions>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Copyright 2021-2021 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.function.adapter.aws;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.Context;
|
||||
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.cloud.function.context.catalog.FunctionTypeUtils;
|
||||
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry.FunctionInvocationWrapper;
|
||||
import org.springframework.cloud.function.json.JsonMapper;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.MessageHeaders;
|
||||
import org.springframework.messaging.support.MessageBuilder;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Oleg Zhurakousky
|
||||
*
|
||||
*/
|
||||
final class AWSLambdaUtils {
|
||||
|
||||
private static Log logger = LogFactory.getLog(AWSLambdaUtils.class);
|
||||
|
||||
private AWSLambdaUtils() {
|
||||
|
||||
}
|
||||
|
||||
public static Message<byte[]> generateMessage(byte[] payload, MessageHeaders headers,
|
||||
FunctionInvocationWrapper function, JsonMapper mapper) {
|
||||
return generateMessage(payload, headers, function, mapper, null);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public static Message<byte[]> generateMessage(byte[] payload, MessageHeaders headers,
|
||||
FunctionInvocationWrapper function, JsonMapper mapper, @Nullable Context awsContext) {
|
||||
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Incoming JSON for ApiGateway Event: " + new String(payload));
|
||||
}
|
||||
|
||||
MessageBuilder messageBuilder = null;
|
||||
Object request = mapper.fromJson(payload, Object.class);
|
||||
Type inputType = function.getInputType();
|
||||
if (FunctionTypeUtils.isMessage(inputType)) {
|
||||
inputType = FunctionTypeUtils.getImmediateGenericType(inputType, 0);
|
||||
}
|
||||
boolean mapInputType = (inputType instanceof ParameterizedType && ((Class<?>) ((ParameterizedType) inputType).getRawType()).isAssignableFrom(Map.class));
|
||||
if (request instanceof Map) {
|
||||
Map<String, ?> requestMap = (Map<String, ?>) request;
|
||||
if (requestMap.containsKey("Records")) {
|
||||
List<Map<String, ?>> records = (List<Map<String, ?>>) requestMap.get("Records");
|
||||
Assert.notEmpty(records, "Incoming event has no records: " + requestMap);
|
||||
logEvent(records);
|
||||
messageBuilder = MessageBuilder.withPayload(payload);
|
||||
}
|
||||
else if (requestMap.containsKey("httpMethod")) { // API Gateway
|
||||
logger.info("Incoming request is API Gateway");
|
||||
if (inputType.getTypeName().endsWith(APIGatewayProxyRequestEvent.class.getSimpleName())) {
|
||||
APIGatewayProxyRequestEvent gatewayEvent = mapper.fromJson(requestMap, APIGatewayProxyRequestEvent.class);
|
||||
messageBuilder = MessageBuilder.withPayload(gatewayEvent);
|
||||
}
|
||||
else if (mapInputType) {
|
||||
messageBuilder = MessageBuilder.withPayload(requestMap).setHeader("httpMethod", requestMap.get("httpMethod"));
|
||||
}
|
||||
else {
|
||||
Object body = requestMap.remove("body");
|
||||
body = body instanceof String ? String.valueOf(body).getBytes(StandardCharsets.UTF_8) : mapper.toJson(body);
|
||||
messageBuilder = MessageBuilder.withPayload(body).copyHeaders(requestMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (messageBuilder == null) {
|
||||
messageBuilder = MessageBuilder.withPayload(payload);
|
||||
}
|
||||
if (awsContext != null) {
|
||||
messageBuilder.setHeader("aws-context", awsContext);
|
||||
}
|
||||
return messageBuilder.copyHeaders(headers).build();
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public static byte[] generateOutput(Message requestMessage, Message<byte[]> responseMessage,
|
||||
JsonMapper mapper) {
|
||||
byte[] responseBytes = responseMessage.getPayload();
|
||||
if (requestMessage.getHeaders().containsKey("httpMethod") || requestMessage.getPayload() instanceof APIGatewayProxyRequestEvent) { // API Gateway
|
||||
Map<String, Object> response = new HashMap<String, Object>();
|
||||
response.put("isBase64Encoded", false);
|
||||
|
||||
MessageHeaders headers = responseMessage.getHeaders();
|
||||
int statusCode = headers.containsKey("statusCode")
|
||||
? (int) headers.get("statusCode")
|
||||
: 200;
|
||||
|
||||
response.put("statusCode", statusCode);
|
||||
if (isRequestKinesis(requestMessage)) {
|
||||
HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
|
||||
response.put("statusDescription", httpStatus.toString());
|
||||
}
|
||||
|
||||
String body = new String(responseMessage.getPayload(), StandardCharsets.UTF_8).replaceAll("\\\"", "\"");
|
||||
response.put("body", body);
|
||||
|
||||
Map<String, String> responseHeaders = new HashMap<>();
|
||||
headers.keySet().forEach(key -> responseHeaders.put(key, headers.get(key).toString()));
|
||||
|
||||
response.put("headers", responseHeaders);
|
||||
responseBytes = mapper.toJson(response);
|
||||
}
|
||||
|
||||
return responseBytes;
|
||||
}
|
||||
|
||||
private static void logEvent(List<Map<String, ?>> records) {
|
||||
if (isKinesisEvent(records.get(0))) {
|
||||
logger.info("Incoming request is Kinesis Event");
|
||||
}
|
||||
else if (isS3Event(records.get(0))) {
|
||||
logger.info("Incoming request is S3 Event");
|
||||
}
|
||||
else if (isSNSEvent(records.get(0))) {
|
||||
logger.info("Incoming request is SNS Event");
|
||||
}
|
||||
else {
|
||||
logger.info("Incoming request is SQS Event");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isRequestKinesis(Message<Object> requestMessage) {
|
||||
return requestMessage.getHeaders().containsKey("Records");
|
||||
}
|
||||
|
||||
private static boolean isSNSEvent(Map<String, ?> record) {
|
||||
return record.containsKey("Sns");
|
||||
}
|
||||
|
||||
private static boolean isS3Event(Map<String, ?> record) {
|
||||
return record.containsKey("s3");
|
||||
}
|
||||
|
||||
private static boolean isKinesisEvent(Map<String, ?> record) {
|
||||
return record.containsKey("kinesis");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* Copyright 2021-2021 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.cloud.function.adapter.aws;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.cloud.function.context.FunctionCatalog;
|
||||
import org.springframework.cloud.function.context.catalog.SimpleFunctionRegistry.FunctionInvocationWrapper;
|
||||
import org.springframework.cloud.function.json.JsonMapper;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.RequestEntity;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.MessageHeaders;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Oleg Zhurakousky
|
||||
* @since 3.1.1
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
@ConditionalOnProperty("AWS_LAMBDA_RUNTIME_API")
|
||||
public class CustomRuntimeEventLoop {
|
||||
|
||||
private static Log logger = LogFactory.getLog(CustomRuntimeEventLoop.class);
|
||||
|
||||
private static final String LAMBDA_VERSION_DATE = "2018-06-01";
|
||||
private static final String LAMBDA_RUNTIME_URL_TEMPLATE = "http://{0}/{1}/runtime/invocation/next";
|
||||
private static final String LAMBDA_INVOCATION_URL_TEMPLATE = "http://{0}/{1}/runtime/invocation/{2}/response";
|
||||
|
||||
@Bean
|
||||
@ConditionalOnProperty("AWS_LAMBDA_RUNTIME_API")
|
||||
public CommandLineRunner backgrounder(ApplicationContext applicationContext) {
|
||||
return args -> eventLoop(applicationContext);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static void eventLoop(ApplicationContext context) {
|
||||
logger.info("Starting spring-cloud-function CustomRuntimeEventLoop");
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("AWS LAMBDA ENVIRONMENT: " + System.getenv());
|
||||
}
|
||||
|
||||
String runtimeApi = System.getenv("AWS_LAMBDA_RUNTIME_API");
|
||||
String eventUri = MessageFormat.format(LAMBDA_RUNTIME_URL_TEMPLATE, runtimeApi, LAMBDA_VERSION_DATE);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Event URI: " + eventUri);
|
||||
}
|
||||
|
||||
RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(eventUri)).build();
|
||||
FunctionCatalog functionCatalog = context.getBean(FunctionCatalog.class);
|
||||
RestTemplate rest = new RestTemplate();
|
||||
JsonMapper mapper = context.getBean(JsonMapper.class);
|
||||
|
||||
logger.info("Entering event loop");
|
||||
while (true) {
|
||||
logger.debug("Attempting to get new event");
|
||||
ResponseEntity<String> response = rest.exchange(requestEntity, String.class);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("New Event received: " + response.getBody());
|
||||
}
|
||||
|
||||
FunctionInvocationWrapper function = locateFunction(functionCatalog, response.getHeaders().getContentType());
|
||||
|
||||
Message<byte[]> eventMessage = AWSLambdaUtils.generateMessage(response.getBody().getBytes(StandardCharsets.UTF_8),
|
||||
fromHttp(response.getHeaders()), function, mapper);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Event message: " + eventMessage);
|
||||
}
|
||||
|
||||
String requestId = response.getHeaders().getFirst("Lambda-Runtime-Aws-Request-Id");
|
||||
String invocationUrl = MessageFormat
|
||||
.format(LAMBDA_INVOCATION_URL_TEMPLATE, runtimeApi, LAMBDA_VERSION_DATE, requestId);
|
||||
|
||||
Message<byte[]> responseMessage = (Message<byte[]>) function.apply(eventMessage);
|
||||
|
||||
String reply = new String(responseMessage.getPayload(), StandardCharsets.UTF_8);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Reply from function: " + reply);
|
||||
}
|
||||
|
||||
byte[] outputBody = AWSLambdaUtils.generateOutput(eventMessage, responseMessage, mapper);
|
||||
ResponseEntity<Object> result = rest
|
||||
.exchange(RequestEntity.post(URI.create(invocationUrl)).body(outputBody), Object.class);
|
||||
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Result POST status: " + result.getStatusCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static FunctionInvocationWrapper locateFunction(FunctionCatalog functionCatalog, MediaType contentType) {
|
||||
String handlerName = System.getenv("_HANDLER");
|
||||
FunctionInvocationWrapper function = functionCatalog.lookup(handlerName, contentType.toString());
|
||||
if (function == null) {
|
||||
handlerName = System.getenv("spring.cloud.function.definition");
|
||||
}
|
||||
function = functionCatalog.lookup(handlerName, contentType.toString());
|
||||
Assert.notNull(function, "Failed to locate function. Tried locating default function, "
|
||||
+ "function by '_HANDLER' env variable as well as'spring.cloud.function.definition'.");
|
||||
if (function != null && logger.isInfoEnabled()) {
|
||||
logger.info("Located function " + function.getFunctionDefinition());
|
||||
}
|
||||
return function;
|
||||
}
|
||||
|
||||
private static MessageHeaders fromHttp(HttpHeaders headers) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
for (String name : headers.keySet()) {
|
||||
Collection<?> values = multi(headers.get(name));
|
||||
name = name.toLowerCase();
|
||||
Object value = values == null ? null
|
||||
: (values.size() == 1 ? values.iterator().next() : values);
|
||||
if (name.toLowerCase().equals(HttpHeaders.CONTENT_TYPE.toLowerCase())) {
|
||||
name = MessageHeaders.CONTENT_TYPE;
|
||||
}
|
||||
map.put(name, value);
|
||||
}
|
||||
return new MessageHeaders(map);
|
||||
}
|
||||
|
||||
private static Collection<?> multi(Object value) {
|
||||
return value instanceof Collection ? (Collection<?>) value : Arrays.asList(value);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
* @author Oleg Zhurakousky
|
||||
*/
|
||||
@Order(0)
|
||||
public class CustomRuntimeInitializer implements ApplicationContextInitializer<GenericApplicationContext> {
|
||||
@@ -35,9 +36,14 @@ public class CustomRuntimeInitializer implements ApplicationContextInitializer<G
|
||||
Boolean enabled = context.getEnvironment().getProperty("spring.cloud.function.web.export.enabled",
|
||||
Boolean.class);
|
||||
if (enabled == null || !enabled) {
|
||||
return;
|
||||
if (StringUtils.hasText(System.getenv("AWS_LAMBDA_RUNTIME_API"))) {
|
||||
if (context.getBeanFactory().getBeanNamesForType(CustomRuntimeEventLoop.class, false, false).length == 0) {
|
||||
context.registerBean(StringUtils.uncapitalize(CustomRuntimeEventLoop.class.getSimpleName()),
|
||||
CommandLineRunner.class, () -> args -> CustomRuntimeEventLoop.eventLoop(context));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ContextFunctionCatalogInitializer.enabled
|
||||
else if (ContextFunctionCatalogInitializer.enabled
|
||||
&& context.getEnvironment().getProperty("spring.functional.enabled", Boolean.class, false)) {
|
||||
if (context.getBeanFactory().getBeanNamesForType(DestinationResolver.class, false, false).length == 0) {
|
||||
context.registerBean(LambdaDestinationResolver.class, () -> new LambdaDestinationResolver());
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
org.springframework.cloud.function.adapter.aws.CustomRuntimeAutoConfiguration
|
||||
org.springframework.cloud.function.adapter.aws.CustomRuntimeEventLoop
|
||||
org.springframework.context.ApplicationContextInitializer=\
|
||||
org.springframework.cloud.function.adapter.aws.CustomRuntimeInitializer
|
||||
org.springframework.boot.env.EnvironmentPostProcessor=\
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
This sample uses the custom runtime type on AWS lambda using @Bean style configuration.
|
||||
However, changing configuration to functional bean registration is supported as well and shown in `function-sample-aws-custom` example.
|
||||
|
||||
To run the app in AWS choose the "Custom Runtime" runtime type, and upload the
|
||||
.zip file that gets built on the command line with `mvn package` (look
|
||||
in `target`).
|
||||
There are several functions defined in the `com.example.LambdaApplication`, so identify the selected function in "Handler"
|
||||
You can also use function composition (e.g., `uppercase|reverse`)
|
||||
|
||||
You can test any function in this example with any String as input, but the Lambda UI only allows valid JSON as
|
||||
test data, so you will have to escape the input with double quotes.
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.4.2-SNAPSHOT</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>io.spring.sample</groupId>
|
||||
<artifactId>function-sample-aws-custom-bean</artifactId>
|
||||
<version>3.0.0.RELEASE</version>
|
||||
<name>AWS Custom Runtime - @Bean sample</name>
|
||||
<description>Demo project for Spring Cloud Function with custom AWS Lambda runtime using @Bean style</description>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<wrapper.version>1.0.22.RELEASE</wrapper.version>
|
||||
<spring-cloud-function.version>3.1.1-SNAPSHOT</spring-cloud-function.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<!--
|
||||
We don't need this dependency unless explicitly using APIGatewayProxyRequestEvent
|
||||
(as on of the function in this example)
|
||||
-->
|
||||
<groupId>com.amazonaws</groupId>
|
||||
<artifactId>aws-lambda-java-events</artifactId>
|
||||
<version>2.2.6</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-function-adapter-aws</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-jdk14</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers</artifactId>
|
||||
<version>1.14.3</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-function-dependencies</artifactId>
|
||||
<version>${spring-cloud-function.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>com/example/ContainerTests.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<configuration>
|
||||
<skip>true</skip>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot.experimental</groupId>
|
||||
<artifactId>spring-boot-thin-layout</artifactId>
|
||||
<version>${wrapper.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>zip</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<inherited>false</inherited>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<descriptors>
|
||||
<descriptor>src/assembly/zip.xml</descriptor>
|
||||
</descriptors>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>none</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>com/example/ContainerTests.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<!-- <repositories> -->
|
||||
<!-- <repository> -->
|
||||
<!-- <id>spring-snapshots</id> -->
|
||||
<!-- <name>Spring Snapshots</name> -->
|
||||
<!-- <url>https://repo.spring.io/libs-snapshot-local</url> -->
|
||||
<!-- <snapshots> -->
|
||||
<!-- <enabled>true</enabled> -->
|
||||
<!-- </snapshots> -->
|
||||
<!-- <releases> -->
|
||||
<!-- <enabled>false</enabled> -->
|
||||
<!-- </releases> -->
|
||||
<!-- </repository> -->
|
||||
<!-- <repository> -->
|
||||
<!-- <id>spring-milestones</id> -->
|
||||
<!-- <name>Spring Milestones</name> -->
|
||||
<!-- <url>https://repo.spring.io/libs-milestone-local</url> -->
|
||||
<!-- <snapshots> -->
|
||||
<!-- <enabled>false</enabled> -->
|
||||
<!-- </snapshots> -->
|
||||
<!-- </repository> -->
|
||||
<!-- <repository> -->
|
||||
<!-- <id>spring-releases</id> -->
|
||||
<!-- <name>Spring Releases</name> -->
|
||||
<!-- <url>https://repo.spring.io/release</url> -->
|
||||
<!-- <snapshots> -->
|
||||
<!-- <enabled>false</enabled> -->
|
||||
<!-- </snapshots> -->
|
||||
<!-- </repository> -->
|
||||
<!-- </repositories> -->
|
||||
<!-- <pluginRepositories> -->
|
||||
<!-- <pluginRepository> -->
|
||||
<!-- <id>spring-snapshots</id> -->
|
||||
<!-- <name>Spring Snapshots</name> -->
|
||||
<!-- <url>https://repo.spring.io/libs-snapshot-local</url> -->
|
||||
<!-- <snapshots> -->
|
||||
<!-- <enabled>true</enabled> -->
|
||||
<!-- </snapshots> -->
|
||||
<!-- <releases> -->
|
||||
<!-- <enabled>false</enabled> -->
|
||||
<!-- </releases> -->
|
||||
<!-- </pluginRepository> -->
|
||||
<!-- <pluginRepository> -->
|
||||
<!-- <id>spring-milestones</id> -->
|
||||
<!-- <name>Spring Milestones</name> -->
|
||||
<!-- <url>https://repo.spring.io/libs-milestone-local</url> -->
|
||||
<!-- <snapshots> -->
|
||||
<!-- <enabled>false</enabled> -->
|
||||
<!-- </snapshots> -->
|
||||
<!-- </pluginRepository> -->
|
||||
<!-- <pluginRepository> -->
|
||||
<!-- <id>spring-releases</id> -->
|
||||
<!-- <name>Spring Releases</name> -->
|
||||
<!-- <url>https://repo.spring.io/libs-release-local</url> -->
|
||||
<!-- <snapshots> -->
|
||||
<!-- <enabled>false</enabled> -->
|
||||
<!-- </snapshots> -->
|
||||
<!-- </pluginRepository> -->
|
||||
<!-- </pluginRepositories> -->
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 https://maven.apache.org/xsd/assembly-1.1.2.xsd">
|
||||
<id>zip</id>
|
||||
<formats>
|
||||
<format>zip</format>
|
||||
</formats>
|
||||
<baseDirectory></baseDirectory>
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<directory>target/classes</directory>
|
||||
<outputDirectory>/</outputDirectory>
|
||||
<useDefaultExcludes>true</useDefaultExcludes>
|
||||
<excludes>
|
||||
<exclude>bootstrap</exclude>
|
||||
</excludes>
|
||||
</fileSet>
|
||||
<fileSet>
|
||||
<directory>target/classes</directory>
|
||||
<outputDirectory>/</outputDirectory>
|
||||
<useDefaultExcludes>true</useDefaultExcludes>
|
||||
<fileMode>0775</fileMode>
|
||||
<includes>
|
||||
<include>bootstrap</include>
|
||||
</includes>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
<dependencySets>
|
||||
<dependencySet>
|
||||
<outputDirectory>/lib</outputDirectory>
|
||||
<unpack>false</unpack>
|
||||
<scope>runtime</scope>
|
||||
</dependencySet>
|
||||
</dependencySets>
|
||||
</assembly>
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.example;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
|
||||
|
||||
@SpringBootApplication
|
||||
public class LambdaApplication {
|
||||
|
||||
private static Log logger = LogFactory.getLog(LambdaApplication.class);
|
||||
|
||||
@Bean
|
||||
public Function<String, String> uppercase() {
|
||||
return value -> {
|
||||
logger.info("UPPERCASING: " + value);
|
||||
return value.toUpperCase();
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Function<APIGatewayProxyRequestEvent, String> extractPayloadFromGatewayEvent() {
|
||||
return value -> {
|
||||
logger.info("ECHO Payload from Gateway Event: " + value.getBody());
|
||||
return value.getBody();
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Function<Message<String>, Message<String>> echoMessage() {
|
||||
return value -> {
|
||||
logger.info("ECHO MESSAGE: " + value);
|
||||
return value;
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Function<String, String> reverse() {
|
||||
return value -> {
|
||||
logger.info("REVERSING: " + value);
|
||||
return new StringBuilder(value).reverse().toString();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("=====> ENVIRONMENT: " + System.getenv("AWS_LAMBDA_RUNTIME_API"));
|
||||
//FunctionalSpringApplication.run(LambdaApplication.class, args);
|
||||
logger.info("==> Starting: LambdaApplication");
|
||||
if (!ObjectUtils.isEmpty(args)) {
|
||||
logger.info("==> args: " + Arrays.asList(args));
|
||||
}
|
||||
SpringApplication.run(LambdaApplication.class, args);
|
||||
}
|
||||
|
||||
// @Override
|
||||
// public void initialize(GenericApplicationContext context) {
|
||||
// context.registerBean("uppercase", FunctionRegistration.class,
|
||||
// () -> new FunctionRegistration<>(uppercase()).type(
|
||||
// FunctionType.from(String.class).to(String.class)));
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
spring.main.web-application-type=none
|
||||
logging.level.org.springframework.cloud=DEBUG
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
|
||||
cd ${LAMBDA_TASK_ROOT:-.}
|
||||
|
||||
java -Dspring.main.web-application-type=none -Dspring.jmx.enabled=false \
|
||||
-noverify -XX:TieredStopAtLevel=1 -Xss256K -XX:MaxMetaspaceSize=128M \
|
||||
-Djava.security.egd=file:/dev/./urandom \
|
||||
-cp .:`echo lib/*.jar | tr ' ' :` com.example.LambdaApplication
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
|
||||
while true
|
||||
do
|
||||
sleep 1
|
||||
done
|
||||
Reference in New Issue
Block a user