Как устранить исключение нулевого указателя при запуске AWS Lambda на основе функции Cloud Cloud - PullRequest
0 голосов
/ 18 июня 2019

Я пытаюсь загрузить простое приложение с весенней загрузкой в ​​AWS lambda, но каждый раз, когда я получаю исключение нулевого указателя при вызове его из Lambda, ниже я публикую код

DemoApplication

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
 } 

SpringBootLambdaHandler

 package com.example.demo;
 import org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler;

 public class SpringBootLambdaHandler extends 
 SpringBootRequestHandler<String,String>{

 }

UpperCaseStringHandler

package com.example.demo;
import java.util.function.Function;
import org.springframework.stereotype.Component;

@Component
public class UpperCaseStringHandler implements Function<String,String> 
   {

   @Override
    public String apply(String input) {
    return input.toUpperCase();
    }
  }

application.properties

 spring.cloud.function.scan.packages=com.example.demo
 cloud.aws.region.auto=false
 cloud.aws.region.static=us-east-1
 cloud.aws.stack.auto = false
 MAIN_CLASS = com.example.demo.DemoApplication
 function.name=upperCaseStringHandler

pom.xml

 <?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 http://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.1.5.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-aws</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-function-adapter-aws</artifactId>
    </dependency>


    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-lambda-java-core</artifactId>
        <version>1.2.0</version>
    </dependency>

</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot.experimental</groupId>
            <artifactId>spring-boot-thin-layout</artifactId>
            <version>1.0.7</version>
        </plugin>
    </plugins>
</build>

</project>

Получениениже исключения

  {
  "errorMessage": "java.lang.NullPointerException",
  "errorType": "java.lang.NullPointerException",
  "stackTrace": [
"org.springframework.cloud.function.context.FunctionalSpringApplication.postProcessApplicationContext(FunctionalSpringApplication.java:102)",
"org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:372)",
"org.springframework.boot.SpringApplication.run(SpringApplication.java:314)",
"org.springframework.cloud.function.adapter.aws.SpringFunctionInitializer.initialize(SpringFunctionInitializer.java:86)",
"org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler.handleRequest(SpringBootRequestHandler.java:46)"
 ]
}

вывод журнала

java.lang.NullPointerException: null
at org.springframework.cloud.function.context.FunctionalSpringApplication.postProcessApplicationContext(FunctionalSpringApplication.java:102) ~[task/:na]
at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:372) ~[task/:na]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) ~[task/:na]
at org.springframework.cloud.function.adapter.aws.SpringFunctionInitializer.initialize(SpringFunctionInitializer.java:86) [task/:na]
at org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler.handleRequest(SpringBootRequestHandler.java:46) [task/:na]
at lambdainternal.EventHandlerLoader$PojoHandlerAsStreamHandler.handleRequest(EventHandlerLoader.java:178) [LambdaSandboxJava-1.0.jar:na]
at lambdainternal.EventHandlerLoader$2.call(EventHandlerLoader.java:888) [LambdaSandboxJava-1.0.jar:na]
at lambdainternal.AWSLambda.startRuntime(AWSLambda.java:293) [LambdaSandboxJava-1.0.jar:na]
at lambdainternal.AWSLambda.<clinit>(AWSLambda.java:64) [LambdaSandboxJava-1.0.jar:na]
at java.lang.Class.forName0(Native Method) [na:1.8.0_201]
at java.lang.Class.forName(Class.java:348) [na:1.8.0_201]
at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:114) [LambdaJavaRTEntry-1.0.jar:na]

java.lang.NullPointerException: java.lang.NullPointerException
java.lang.NullPointerException
at  org.springframework.cloud.function.context.FunctionalSpringApplication.postProcessApplicationContext(FunctionalSpringApplication.java:102)
at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:372)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
at org.springframework.cloud.function.adapter.aws.SpringFunctionInitializer.initialize(SpringFunctionInitializer.java:86)
at org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler.handleRequest(SpringBootRequestHandler.java:46)

END RequestId: cf38ac86-b6b6-4248-bb85-84326ae7ad76
REPORT RequestId: cf38ac86-b6b6-4248-bb85-84326ae7ad76  Duration: 
3757.95 ms  Billed Duration: 3800 ms    Memory Size: 512 MB Max Memory 
Used: 106 MB    

Получил ссылку из примера ниже

https://www.baeldung.com/spring-cloud-function

1 Ответ

0 голосов
/ 24 июня 2019

NPE можно решить, добавив ниже env для своей лямбды,

MAIN_CLASS = com.example.demo.DemoApplication

См. эту проблему для более подробной информации

ps:

Я развернул ваш код через безсерверный фреймворк , ниже приведен пример конфигурации без сервера для справки,

service:
  name: spring-cloud-function-npe

frameworkVersion: ">=1.0.0 <2.0.0"

provider:
  name: aws
  runtime: java8
  stage: ${opt:stage, 'dev'} # Set the default stage used. Default is dev
  region: ${opt:region, 'ap-east-1'} # Overwrite the default region used. Default is ap-southeast-1
  stackName: spring-cloud-function-npe-${self:provider.stage} # Use a custom name for the CloudFormation stack
  apiName: spring-cloud-function-npe-${self:provider.stage} # Use a custom name for the API Gateway API
  profile: ${opt:profile, 'default'} # The default profile to use with this service
  memorySize: 1024 # Overwrite the default memory size. Default is 1024
  timeout: 6 # The default is 6 seconds. Note: API Gateway current maximum is 30 seconds
  logRetentionInDays: 14 # Set the default RetentionInDays for a CloudWatch LogGroup
  deploymentPrefix: serverless # The S3 prefix under which deployed artifacts should be stored. Default is serverless
  versionFunctions: true # Optional function versioning
  endpointType: regional # Optional endpoint configuration for API Gateway REST API. Default is Edge.
  logs:
    restApi: true

package:
  individually: true

functions:
  springCloudFunctionDemo:
    handler: com.example.demo.SpringBootLambdaHandler::handleRequest # required, handler set in AWS Lambda
    name: ${self:provider.stage}-spring-cloud-function-npe # optional, Deployed Lambda name
    description: spring-cloud-function-npe # optional, Description to publish to AWS
    memorySize: 384 # optional, in MB, default is 1024
    timeout: 100 # optional, in seconds, default is 6
    reservedConcurrency: 5 # optional, reserved concurrency limit for this function. By default, AWS uses account concurrency limit
    tracing: PassThrough # optional, overwrite, can be 'Active' or 'PassThrough'
    environment: # Function level environment variables
      FUNCTION_NAME: UpperCaseStringHandler
      MAIN_CLASS: com.example.demo.DemoApplication
    package:
      artifact: target/demo-0.0.1-SNAPSHOT.jar

Затем разверните и вызовите лямбду,

sls deploy
sls invoke -f springCloudFunctionDemo --data "hello world"
...