Azure Functions 시나리오

일련의 중요한 이벤트에 대응하는 시스템을 빌드하는 경우가 많습니다. 웹 API를 빌드하든, 데이터베이스 변경에 응답하든, 이벤트 스트림 또는 메시지를 처리하든, Azure Functions를 사용하여 구현할 수 있습니다.

대부분의 경우 함수 는 다양한 기능을 제공하는 클라우드 서비스 배열과 통합됩니다. 다음은 Azure Functions에 대한 일반적인(그러나 완전하지는 않음) 시나리오 집합입니다.

문서 맨 위에 있는 개발 언어를 선택합니다.

파일 업로드 처리

함수를 사용하여 Blob Storage 컨테이너 내/외부로 파일을 처리하는 방법에는 여러 가지가 있습니다. Blob 컨테이너에서 트리거하는 옵션에 대한 자세한 내용은 모범 사례 설명서에서 Blob 작업(Working with Blob)을 참조하세요.

예를 들어 소매 솔루션에서 파트너 시스템은 제품 카탈로그 정보를 Blob Storage에 파일로 제출할 수 있습니다. Blob 트리거 함수를 사용하여 파일이 업로드될 때 파일의 유효성을 검사하고, 변환하고, 기본 시스템으로 처리할 수 있습니다.

Diagram of a file upload process using Azure Functions.

다음 자습서에서는 Event Grid 트리거를 사용하여 Blob 컨테이너의 파일을 처리합니다.

예를 들어 Blob 컨테이너에서 이벤트 구독과 함께 Blob 트리거를 사용합니다.

[FunctionName("ProcessCatalogData")]
public static async Task Run([BlobTrigger("catalog-uploads/{name}", Source = BlobTriggerSource.EventGrid, Connection = "<NAMED_STORAGE_CONNECTION>")]Stream myCatalogData, string name, ILogger log)
{
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myCatalogData.Length} Bytes");

    using (var reader = new StreamReader(myCatalogData))
    {
        var catalogEntry = await reader.ReadLineAsync();
        while(catalogEntry !=null)
        {
            // Process the catalog entry
            // ...

            catalogEntry = await reader.ReadLineAsync();
        }
    }
}

실시간 스트림 및 이벤트 처리

클라우드 애플리케이션, IoT 디바이스 및 네트워킹 디바이스에서 많은 원격 분석이 생성되고 수집됩니다. Azure Functions는 해당 데이터를 거의 실시간으로 핫 경로로 처리한 다음 분석 대시보드에서 사용할 수 있도록 Azure Cosmos DB 에 저장할 수 있습니다.

또한 함수는 Event Grid와 같은 짧은 대기 시간 이벤트 트리거 및 SignalR과 같은 실시간 출력을 사용하여 거의 실시간으로 데이터를 처리할 수 있습니다.

Diagram of a real-time stream process using Azure Functions.

예를 들어 이벤트 허브 트리거를 사용하여 이벤트 허브에서 읽은 다음 출력 바인딩을 사용하여 이벤트를 분리하고 변환한 후 이벤트 허브에 씁니다.

[FunctionName("ProcessorFunction")]
public static async Task Run(
    [EventHubTrigger(
        "%Input_EH_Name%",
        Connection = "InputEventHubConnectionString",
        ConsumerGroup = "%Input_EH_ConsumerGroup%")] EventData[] inputMessages,
    [EventHub(
        "%Output_EH_Name%",
        Connection = "OutputEventHubConnectionString")] IAsyncCollector<SensorDataRecord> outputMessages,
    PartitionContext partitionContext,
    ILogger log)
{
    var debatcher = new Debatcher(log);
    var debatchedMessages = await debatcher.Debatch(inputMessages, partitionContext.PartitionId);

    var xformer = new Transformer(log);
    await xformer.Transform(debatchedMessages, partitionContext.PartitionId, outputMessages);
}

기계 학습 및 AI

데이터 처리 외에도 Azure Functions를 사용하여 모델을 유추할 수 있습니다.

예를 들어 TensorFlow 모델을 호출하거나 Azure AI 서비스에 제출하는 함수는 이미지 스트림을 처리하고 분류할 수 있습니다.

또한 함수는 다른 서비스에 연결하여 데이터를 처리하고 텍스트 요약과 같은 다른 AI 관련 작업을 수행할 수 있습니다.

Diagram of a machine learning and AI process using Azure Functions.

예약된 작업 실행

함수를 사용하면 정의한 cron 일정따라 코드를 실행할 수 있습니다.

일정따라 실행되는 Azure Portal에서 함수를 만드는 방법을 확인합니다.

예를 들어 금융 서비스 고객 데이터베이스는 동일한 고객에게 여러 통신이 진행되지 않도록 15분마다 중복 항목을 분석할 수 있습니다.

Diagram of a scheduled task where a function cleans a database every 15 minutes deduplicating entries based on business logic.

[FunctionName("TimerTriggerCSharp")]
public static void Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer, ILogger log)
{
    if (myTimer.IsPastDue)
    {
        log.LogInformation("Timer is running late!");
    }
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

    // Perform the database deduplication
}

확장 가능한 웹 API 빌드

HTTP 트리거 함수는 HTTP 엔드포인트를 정의합니다. 이러한 엔드포인트는 다른 서비스에 직접 연결하거나 바인딩 확장을 사용하여 연결할 수 있는 함수 코드를 실행합니다. 엔드포인트를 웹 기반 API로 작성할 수 있습니다.

HTTP 트리거 함수 엔드포인트를 웹후크 통합(예: GitHub 웹후크)으로 사용할 수도 있습니다. 이러한 방식으로 GitHub 이벤트에서 데이터를 처리하는 함수를 만들 수 있습니다. 자세한 내용은 Azure Functions에서 웹후크를 사용하여 GitHub 이벤트 모니터링을 참조하세요.

Diagram of processing an HTTP request using Azure Functions.

예제는 다음을 참조하세요.

[FunctionName("InsertName")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
    [CosmosDB(
        databaseName: "my-database",
        collectionName: "my-container",
        ConnectionStringSetting = "CosmosDbConnectionString")]IAsyncCollector<dynamic> documentsOut,
    ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    string name = data?.name;

    if (name == null)
    {
        return new BadRequestObjectResult("Please pass a name in the request body json");
    }

    // Add a JSON document to the output container.
    await documentsOut.AddAsync(new
    {
        // create a random ID
        id = System.Guid.NewGuid().ToString(), 
        name = name
    });

    return new OkResult();
}

서버리스 워크플로 빌드

Functions는 Logic Apps 워크플로와 같은 서버리스 워크플로 토폴로지의 컴퓨팅 구성 요소인 경우가 많습니다. 지속성 함수 확장을 사용하여 장기 실행 오케스트레이션을 만들 수도 있습니다. 자세한 내용은 Durable Functions 개요를 참조하세요.

A combination diagram of a series of specific serverless workflows using Azure Functions.

데이터베이스 변경 내용에 응답

저장된 데이터가 변경될 때 다른 작업을 기록, 감사 또는 수행해야 할 수 있는 프로세스가 있습니다. 함수 트리거는 이러한 작업을 초기화하기 위한 데이터 변경에 대한 알림을 받는 좋은 방법을 제공합니다.

Diagram of a function being used to respond to database changes.

다음 예를 살펴 보십시오.

신뢰할 수 있는 메시지 시스템 만들기

Azure 메시징 서비스와 함께 Functions를 사용하여 고급 이벤트 기반 메시징 솔루션을 만들 수 있습니다.

예를 들어 일련의 함수 실행을 연결하는 방법으로 Azure Storage 큐의 트리거를 사용할 수 있습니다. 또는 온라인 주문 시스템에 대해 Service Bus 큐 및 트리거를 사용합니다.

Diagram of Azure Functions in a reliable message system.

다음 문서에서는 스토리지 큐에 출력을 쓰는 방법을 보여 줍니다.

또한 이러한 문서에서는 Azure Service Bus 큐 또는 토픽에서 트리거하는 방법을 보여 주세요.

다음 단계