AWS/AWS 기초

Serverless component

2로 접어듦 2023. 2. 20. 16:16

Role of 'package.json' for serverless environment

In a serverless environment, the package.json file plays an important role in managing the dependencies and configurations for your serverless functions.

 

The package.json file is a standard file used by Node.js-based projects to define dependencies and scripts required to build and run the project. In a serverless environment, this file is used to define the dependencies required by your serverless function, such as AWS SDK, serverless plugins, and any other third-party libraries that your function may depend on.

 

When you deploy a serverless function, the package manager (such as npm or yarn) reads the package.json file and installs the specified dependencies into the function's deployment package. This ensures that your function has access to all the required dependencies when it's executed in the serverless environment.

 

In addition to dependencies, the package.json file can also be used to define custom scripts that can be executed during the build and deployment process. For example, you can define scripts to run tests, compile code, or deploy the function to AWS.

 

Overall, the package.json file is a key configuration file in a serverless environment that helps manage dependencies and build processes for your serverless functions.

 

Handler.js의 역할(for serverless system)

handler.js 파일은 AWS Lambda를 사용하여 구축된 서버리스 시스템의 중요한 구성 요소 중 하나입니다. 이 파일에는 HTTP 요청, Amazon SNS 토픽에서의 메시지 또는 Amazon S3 버킷에 업로드된 파일과 같은 이벤트가 트리거된 Lambda 함수의 코드가 포함됩니다.

 

handler.js 파일은 Lambda 함수의 진입점을 정의합니다. 이 함수는 함수가 호출될 때 실행되는 JavaScript 함수입니다. 함수는 전달된 이벤트 데이터에 액세스하여 처리하고 응답을 반환할 수 있습니다.

 

handler.js 파일은 일반적으로 이벤트 객체와 컨텍스트 객체 두 가지 인수를 받는 함수를 내보냅니다. 이벤트 객체에는 Lambda 함수를 트리거한 데이터가 포함되어 있으며, 컨텍스트 객체에는 AWS 지역 및 계정 ID와 같은 실행 환경에 관한 정보가 제공됩니다.

handler.js 파일에는 Lambda 함수의 종속성 및 구성 설정도 포함될 수 있습니다. 예를 들어, AWS SDK나 로깅 라이브러리와 같은 외부 모듈이 필요하거나 함수에서 사용되는 환경 변수가 설정될 수 있습니다.

 

전반적으로 handler.js 파일은 서버리스 시스템에서 Lambda 함수의 논리를 정의하는 데 중요한 역할을 합니다. 이 파일은 이벤트를 처리하고 응답을 생성하는 시작점입니다.

 

 

Code Example for Hander.js

// 필요한 라이브러리 가져오기
const AWS = require('aws-sdk');

// 핸들러 함수 정의하기
exports.handler = async (event, context) => {
  try {
    // 들어오는 이벤트 데이터 파싱하기
    const data = JSON.parse(event.body);

    // AWS 서비스를 사용하여 작업 수행하기
    const result = await someAWSService.someOperation(data);

    // 호출자에게 응답 반환하기
    return {
      statusCode: 200,
      body: JSON.stringify(result),
      headers: {
        'Content-Type': 'application/json'
      }
    };
  } catch (err) {
    // 발생하는 모든 오류 처리하기
    console.error(err);

    // 호출자에게 오류 응답 반환하기
    return {
      statusCode: 500,
      body: JSON.stringify({ message: '내부 서버 오류' }),
      headers: {
        'Content-Type': 'application/json'
      }
    };
  }
};

이 예에서 handler.js 파일의 기본 구성 요소는 다음과 같습니다.

  1. 필요한 라이브러리 가져오기: require() 함수를 사용하여 필요한 라이브러리나 모듈을 가져옵니다. 이 예에서는 AWS SDK 라이브러리를 가져와 함수가 AWS 서비스와 상호 작용할 수 있도록 합니다.
  2. 핸들러 함수 정의하기: exports.handler 함수는 람다 함수의 코드 진입점으로 정의됩니다. 이 함수는 람다 함수가 이벤트로 트리거될 때 실행됩니다.
  3. 들어오는 이벤트 데이터 파싱하기: 들어오는 이벤트 데이터를 파싱하고 data 변수에 저장합니다. 이 예에서는 이벤트 데이터가 JSON 형식으로 예상되며 JSON.parse() 함수를 사용하여 파싱됩니다.
  4. AWS 서비스를 사용하여 작업 수행하기: 이 예에서는 someAWSService라는 가상의 AWS 서비스를 사용하여 들어오는 데이터를 사용하여 작업을 수행합니다. 작업의 결과는 result 변수에 저장됩니다.
  5. 호출자에게 응답 반환하기: 함수는 상태 코드, 본문 및 헤더가 포함된 HTTP 응답으로 호출자에게 응답을 반환합니다. JSON.stringify() 함수를 사용하여 result 객체를 JSON 문자열로 변환하여 응답 본문에 사용합니다. 오류가 발생하면 대신 오류 응답이 반환됩니다.

 

"진입점", entry point in Handler.js file

진입점, entry point는 handler.js 파일에서 exports.handler와 같이 정의된다. AWS Lambda에서 해당 이벤트가 발생할 때 실행되는 JavaScript 함수이다. 이벤트가 발생할 때 어떤 동작을 수행할 지 정의하는 것이다.

 

module.exports.listImages 와 같이, 굳이 handler라고 이름을 짓지 않아도 된다.

handler.js 파일은 serverless.yml파일에서 'function' 파트에서 'handler' 지점에서 호출될 것이다, 아래와 같이.

functions:
  analyzeUrl:
    handler: handler.analyzeUrl
    environment:
      BUCKET: ${self:custom.bucket}
      QUEUE: ${self:custom.crawlerqueue}
      REGION: ${self:custom.region}
      ACCOUNTID: ${self:custom.accountid}
    events:
      - http:
          path: url/analyze
          method: post
          cors: true

 

 


Basic Componenst for serverless system on AWS

  1. AWS Lambda: This is a compute service that lets you run your code in response to events, without having to provision or manage servers. It's the core of any serverless system on AWS.
  2. API Gateway: This is a fully managed service that makes it easy for developers to create, publish, and manage APIs. It's used to create RESTful APIs that trigger your Lambda functions.
  3. Amazon S3: This is a storage service that provides industry-leading scalability, data availability, security, and performance. It's commonly used to store static assets such as images, videos, and HTML files that can be served by your Lambda functions.
  4. Amazon DynamoDB: This is a NoSQL database service that provides fast and predictable performance with seamless scalability. It's commonly used as a database for serverless applications.
  5. Amazon SNS: This is a fully managed messaging service that enables you to decouple and scale microservices, distributed systems, and serverless applications. It's commonly used to send notifications and messages between Lambda functions.

These components work together to provide a scalable and flexible architecture for your serverless applications. Lambda functions can be triggered by a variety of events, such as API Gateway requests or S3 object uploads. They can then process data from DynamoDB, store files in S3, and communicate with other functions using SNS.

 

Overall, the combination of Lambda, API Gateway, S3, DynamoDB, and SNS provides a powerful and flexible platform for building serverless applications on AWS.

 

Why DynamoDB? : Flexible with unstructured data, Easy for scaling.

One of the reasons why DynamoDB is a popular choice for serverless applications is because it can be easily integrated with AWS Lambda. Since Lambda functions are designed to be small and stateless, they are a perfect fit for a NoSQL database like DynamoDB. In addition, DynamoDB's flexible data model allows developers to store and query data in a variety of ways, making it easy to adapt to changing application requirements.

 

As for why AWS chose to use a NoSQL database like DynamoDB, one of the main benefits of NoSQL databases is their flexibility. Unlike traditional relational databases, NoSQL databases are schema-less and can handle unstructured and semi-structured data with ease. This makes them ideal for building applications that require flexibility and scalability, such as social media platforms, e-commerce websites, and IoT applications.

NoSQL databases also allow for horizontal scaling, which means that as the volume of data grows, additional nodes can be added to the cluster to handle the increased workload. This makes it easy to scale the database as the application grows, without having to worry about complex data modeling or schema changes.