AWS 를 사용한 서버리스 아키텍쳐 적용기(삽질기) (1) - 람다함수 1
서버리스 아키텍쳐 (serverless architecture) 란?
기존에 서버를 가지고 하던 서비스를 서버가 없이 동작하게 만드는 구조.
(그렇다고 진짜 서버가 없는 것은 아니고, 클라우드를 통해 서버가 없는 것처럼 사용한다는 뜻. 진짜 물리서버는 어딘가에 당연히 있음.)
서버리스를 구축하기 위한 방법에는 여러가지가 있지만 여기서는 서버리스를 구축하기 위해 AWS를 사용합니다.
0. AWS lambda란?
serverless event handling computing service.
다시말해, 서버가 없는 클라우드 함수 기반 마이크로 서비스. 기존의 서비스들은 서버에 코드를 올려 배포한 뒤 서비스를 제공하는 방식이었다면, 람다는 서버에 따로 올려서 서버를 관리할 필요가 없다는 것!! 넘나 좋은 것~
서버가 따로 필요없이 코드만 따로 배포가능. 그리고 서버가 없기 때문에 과금방식은 함수 실행 시 과금되는 방식.
여러가지 장점이 있으니 구글 교수님과 알아보도록 하겠습니다. 물론 단점도 존재. 제대로 사용하려면 이것저것 따져보고 공부도 많이 해야될 듯...
아무튼 이제부터 기초부터 살살 들여다 보겠습니다~!
1. 람다를 클릭해서 들어간 다음 region을 서울로 설정
2. 함수 생성 버튼 클릭.
아래와 같은 화면이 나옵니다. (검색해보니 블루프린트는 사용 용도별 샘플 코드가 모여있음 !! 니즈가 잘 맞으면 사용하면 편할수도?)
하지만 저는 새로 작성 하겠습니다. 왜? (개발자 특, 자기가 다 만들어보고 싶음). Node로 할꺼니깐 node 버전은 8.10 선택! 밑에 권한 설정하는게 있는데 기본 Lambda 권한으로 세팅해주면 됩니다.
함수 생성 버튼 클릭 !
3. 본격적으로 함수 생성.
세부적으로 여러가지 메뉴가 있는데 차근차근 araboza.
맨 처음 보이는 Designer 탭.... 보아하니 다른 아마존 서비스와 묶어 사용할 수 있도록 트리거가 제공되는듯..?
나중에 살펴보도록 하고 함수 코드 부분으로 넘어가겠습니다. 에디터가 요기잉네 ㅎ
저는 드라큘라를 사랑하기 때문에 다크 테마로 바꿨습니다ㅎㅎ. 앞단계에서 런타임을 node로 설정해줬는데 여기서 다시 바꿀 수 있습니다.
이제부터 공식문서를 살펴보면서 코드 분석 시작!!
exports.hello = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
요로케 생겼는데 문서를 읽어보니 람다 함수는 기본적으로 handler 객체를 통해 호출된다고 합니다.
물론 handler 객체는 이름 입력하기 나름. helloWorld 출력할 꺼니깐 함수이름을 hello로 바꾸겠습니다.
그리고 우측 상단에 보면 핸들러 라고 써져있는데 이 부분엔 문맥상 파일 이름하고 함수로 구성된듯 (파일이름.함수 == index.hello)
4. 공식 문서에 람다 함수가 지원하는 호출 유형은 두가지.
첫 번째는 RequestResponse 또는 동기식 실행.
exports.myHandler = function(event, context, callback) {
console.log("value1 = " + event.key1);
console.log("value2 = " + event.key2);
callback(null, "some success message");
// or
// callback("some error type");
}
실행 완료시 코드에서 callback을 호출할 수 있는데 callback이 없으면 Lambda가 자체적으로 callback 호출을 하고 반환 값은 null을 반환합니다. 콜백 형식은 callback(Error error, Object result) 형식. 귀찮으니깐 예제로 ㄱㄱ
callback(); // Indicates success but no information returned to the caller.
callback(null); // Indicates success but no information returned to the caller.
callback(null, "success"); // Indicates success with information returned to the caller.
callback(error); // Indicates error with error information returned to the caller.
result 값은 JSON.stringify와 호환이 가능해야 한다고 나와있습니다.
두 번째는 event 또는 비동기 실행 방식.
exports.myHandler = async function(event, context) {
console.log("value1 = " + event.key1);
console.log("value2 = " + event.key2);
return "some success message";
// or
// throw new Error("some error type");
}
이 경우 람다는 함수 호출의 결과를 모두 폐기합니다. api call 등을 할 때, await나 promise 쓰면 결과적으로 동일하게 작동할 듯.
console.log 를 통해 생성하는 로그 메시지들은 cloudWatch를 통해 기록할 수 있습니다.
이때 함수 인자로 있는 context는 람다에서 핸들러로 쓰이는 객체입니다. 여러 정보를 제공하는 메서드와 속성들을 포함.
컨텍스트 메서드
-
getRemainingTimeInMillis() – Returns the number of milliseconds left before the execution times out.
컨텍스트 속성
-
functionName – The name of the Lambda function.
-
functionVersion – The version of the function.
-
invokedFunctionArn – The Amazon Resource Name (ARN) used to invoke the function. Indicates if the invoker specified a version number or alias.
-
memoryLimitInMB – The amount of memory configured on the function.
-
awsRequestId – The identifier of the invocation request.
-
logGroupName – The log group for the function.
-
logStreamName – The log stream for the function instance.
-
identity – (mobile apps) Information about the Amazon Cognito identity that authorized the request.
-
cognitoIdentityId – The authenticated Amazon Cognito identity.
-
cognitoIdentityPoolId – The Amazon Cognito identity pool that authorized the invocation.
-
-
clientContext – (mobile apps) Client context provided to the Lambda invoker by the client application.
-
client.installation_id
-
client.app_title
-
client.app_version_name
-
client.app_version_code
-
client.app_package_name
-
env.platform_version
-
env.platform
-
env.make
-
env.model
-
env.locale
-
Custom – 모바일 애플리케이션에서 설정된 사용자 지정 값입니다.
-
-
callbackWaitsForEmptyEventLoop – Node.js 이벤트 루프가 빌 때까지 대기하는 대신, 콜백이 실행될 때 즉시 응답을 보내려면 false로 설정합니다. false인 경우, 대기 중인 이벤트는 다음 번 호출 중에 계속 실행됩니다
다음 예제는 컨텍스트 정보를 기록하는 핸들러 함수를 보여줍니다.
예 index.js
exports.handler = function(event, context, callback) {
console.log('remaining time =', context.getRemainingTimeInMillis());
console.log('functionName =', context.functionName);
console.log('AWSrequestID =', context.awsRequestId);
callback(null, context.functionName);
};
나머지는 다음 글에서 이어서 작성!