AWS Lambda로 Spring Project Serverless 구성하기

정 승 연·2023년 8월 10일
0

목록 보기
8/9

Spring Project를 Lambda에 적용시키는 방법을 찾아보았을 때,

Function<APIGatewayProxyRequestEvent, Response > 인터페이스 사용을 알게되었다.

API Gateway 를 이용해 Lambda가 사용되는 것이 목적이기에 APIGatewayProxyRequestEvent 를 사용하였다.

build.gradle


	implementation 'org.springframework.cloud:spring-cloud-function-adapter-aws'
	implementation 'org.springframework.cloud:spring-cloud-starter-function-web'

	implementation 'com.amazonaws:aws-lambda-java-core:1.2.2'
	implementation 'com.amazonaws:aws-lambda-java-events:3.11.1'
    
    ...
    
    task buildZip(type: Zip) {
	from compileJava
	from processResources
	into('lib') {
		from configurations.runtimeClasspath
	}
}

application.properties

spring.cloud.function.definition=lambdaApiGatewayFunctionBean

main class
진행하고 싶은 함수의 로직이 있는 클래스로, apply 메소드를 오버라이딩 하여 로직을 구현한다.

package ascssu.handson.Lambda;

import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.function.Function;

@Component
@Slf4j
public class HandsOn implements Function<APIGatewayProxyRequestEvent, AdultJudgeResponse> {

    @Override
    public AdultJudgeResponse apply(APIGatewayProxyRequestEvent request) {

        UserRequest userRequest = new UserRequest();

        if (StringUtils.hasText(request.getBody())) {
            try {
                userRequest = new ObjectMapper().readValue(request.getBody(), UserRequest.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

            if (userRequest.getAge() > 20) {
                return new AdultJudgeResponse(userRequest.getName() + "은(는) 성인입니다.");
            }

                return new AdultJudgeResponse(userRequest.getName()  + "은(는) 성인이 아닙니다.");
            }
}

LambdaApiGateWayHandler

public class LambdaApiGateWayHandler extends FunctionInvoker {
}

UserRequest

public class UserRequest {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

실행해보기

굳이 . .안해봐도 되긴 함니다 ..

curl -v -X POST \\
  'http://localhost:8080/handsOn' \
  -H 'Content-Type: application/json' \
  -d '{"name":"seungyeon","age":24}'

Zip 파일 만들기

AWS S3에 jar 파일 올려야 하기때문에 build.gradle에 zip 파일 만드는 task 적어둔 것을 실행시킨다.

AWS S3 버킷 만들기


AWS S3 버킷에 프로젝트 파일 업로드


Lambda 에 올릴 프로젝트 객체입니다. 객체 주소 복사해두기.

Lambda 함수 생성

S3 URL로 Lambda 함수에 프로젝트 파일 추가

런타임 설정 편집

구성-환경변수-편집

환경 변수 입력


일단 AWS Console 상 테스트 성공

API Gateway 트리거 추가

API Gateway Trigger 연결 성공

API Gateway 엔드포인트 얻기

Postman 이용한 테스트도 성공!

참고 자료
Project Github

0개의 댓글