programing

Azure 함수 내에서 다른 함수를 호출하는 방법

sourcejob 2023. 5. 29. 10:37
반응형

Azure 함수 내에서 다른 함수를 호출하는 방법

저는 다음과 같이 3가지 기능을 작성했습니다.

  1. DB에 사용자 생성
  2. DB에서 사용자 가져오기
  3. 프로세스 사용자

[3] 함수에서는 아래와 같이 [2] 함수를 호출하여 사용자가 Azure 함수 url을 사용하도록 하겠습니다:-

https://hdidownload.azurewebsites.net/api/getusers

위와 같이 전체 경로 없이 다른 Azure 함수 내에서 Azure 함수를 호출할 수 있는 다른 방법이 있습니까?

함수 앱에는 실제로 HTTP를 호출하지 않고 다른 함수에서 하나의 HTTP 함수를 호출하는 기능이 내장되어 있지 않습니다.

간단한 사용 사례의 경우 전체 URL로 전화하는 것을 고수할 것입니다.

고급 워크플로우를 보려면 Durable Functions, 특히 Function Chaining살펴보십시오.

이전 답변은 모두 유효하지만, 의견에도 언급했듯이 올해 초(2018년 1분기/2분기)에 내구성 기능의 개념이 도입되었습니다.간단히 말해, 내구성 기능:

서버가 없는 환경에서 상태 저장 함수를 작성할 수 있습니다.확장은 상태, 체크포인트 및 재시작을 관리합니다.

이는 여러 기능을 체인으로 연결할 수 있다는 것을 의미합니다.만약 당신이 이것이 필요하다면, 그것은 기능 A => B => C에서 흐를 때 상태를 관리합니다.

Function App에 Durable Functions Extension을 설치하면 작동합니다.이를 통해 예를 들어 C#에서 다음과 같은 작업을 수행할 수 있는 몇 가지 새로운 컨텍스트 바인딩을 사용할 수 있습니다(의사 코드).

[FunctionName("ExpensiveDurableSequence")]
public static async Task<List<string>> Run(
    [OrchestrationTrigger] DurableOrchestrationTrigger context)
{
    var response = new List<Order>();

    // Call external function 1 
    var token = await context.CallActivityAsync<string>("GetDbToken", "i-am-root");

    // Call external function 2
    response.Add(await context.CallActivityAsync<IEnumerable<Order>>("GetOrdersFromDb", token));

    return response;
}

[FunctionName("GetDbToken")]
public static string GetDbToken([ActivityTrigger] string username)
{
    // do expensive remote api magic here
    return token;
}

[FunctionaName("GetOrdersFromDb")]
public static IEnumerable<Order> GetOrdersFromDb([ActivityTrigger] string apikey)
{
    // do expensive db magic here
    return orders;
}

몇 가지 좋은 점은 다음과 같습니다.

  • 주 시퀀스는 연속적으로 실행되는 두 개의 추가 기능을 연결합니다.
  • 외부 함수가 실행되면 주 시퀀스가 절전 모드로 전환됩니다. 즉, 외부 함수가 처리 중인 경우 두 번 청구되지 않습니다.

이를 통해 여러 기능을 서로 순차적으로 실행하거나(예: 기능 체인) 여러 기능을 동시에 실행하고 모두 완료될 때까지 기다릴 수 있습니다(팬아웃/팬인).

이에 대한 추가 배경 참조:

내구성 기능이 있다는 것은 알고 있지만 일반적인 정적 방법처럼 기능을 호출하고 작동합니다. 예를 들어 다음과 같습니다.

public static class HelloWorld
{
    [FunctionName("HelloWorld")]
    public static string Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log)
    {
        return "Hello World";
    }

}

public static class HelloWorldCall
{
    [FunctionName("HelloWorldCall")]
    public static string Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log)
    {
        var caller = HelloWorld.Run(req, log);
        return caller;
    }

}

일반적인 C# static 방식으로 두 번째 기능을 호출하여 직접 할 수 있습니다.

그러나 이 경우 Azure Functions 확장 및 배포의 이점을 잃게 됩니다(예: 서버 로드에 따라 두 번째 기능을 세계 다른 지역에서 호출할 수 있음).

  1. 다른 함수의 공용 URL로 HTTP 요청 보내기
  2. 메시지를 Azure 큐에 넣고 다른 Azure 함수가 메시지를 처리하도록 합니다.
  3. 내구성 기능 사용

C#의 첫 번째 옵션에 대해서는 다음과 같이 할 수 있습니다.

    static HttpClient client = new HttpClient();

    [FunctionName("RequestImageProcessing")]
    public static async Task RequestImageProcessing([HttpTrigger(WebHookType = "genericJson")]
        HttpRequestMessage req)
    {
            string anotherFunctionSecret = ConfigurationManager.AppSettings
                ["AnotherFunction_secret"];
            // anotherFunctionUri is another Azure Function's 
            // public URL, which should provide the secret code stored in app settings 
            // with key 'AnotherFunction_secret'
            Uri anotherFunctionUri = new Uri(req.RequestUri.AbsoluteUri.Replace(
                req.RequestUri.PathAndQuery, 
                $"/api/AnotherFunction?code={anotherFunctionSecret}"));

            var responseFromAnotherFunction = await client.GetAsync(anotherFunctionUri);
            // process the response

    }

    [FunctionName("AnotherFunction")]
    public static async Task AnotherFunction([HttpTrigger(WebHookType = "genericJson")]
    HttpRequestMessage req)
    {
        await Worker.DoWorkAsync();
    }

또한 HTTP 응답을 먼저 반환하고 백그라운드에서 작업을 수행하기 위해 첫 번째 Azure 함수가 필요할 때도 있습니다. 그러면 이 솔루션이 작동하지 않습니다.이 경우 옵션 2와 3이 적합합니다.

저는 좋은 자료를 찾지 못했고, 아래와 같이 했는데, 잘 작동했습니다.

아래 형식의 URL로 다른 함수를 호출하려면:

https://my-functn-app-1.azurewebsites.net/some-path-here1?code=123412somecodehereemiii888ii88k123m123l123k1l23k1l3==

Node.js에서 다음과 같이 전화했습니다.

let request_options = {
        method: 'GET',
        host: 'my-functn-app-1.azurewebsites.net',
        path: '/path1/path2?&q1=v1&q2=v2&code=123412somecodehereemiii888ii88k123m123l123k1l23k1l3',
        headers: {
            'Content-Type': 'application/json'
        }
};
require('https')
    .request(
         request_options,
         function (res) {
               // do something here
         });

문제없이 작동했습니다.
다른 프로그래밍 언어에서도 비슷한 방식으로 작동해야 합니다.
이게 도움이 되길 바랍니다.

내구성 기능를 지원하지만 현재 C#, F# 또는 JavaScript를 사용하는 경우에만 지원됩니다.

다른 옵션은 다음과 같습니다.

  1. 새 Azure 함수에 대한 HTTP 요청을 생성하지만, 함수가 응답을 기다리지 않는 방식으로 만들어야 합니다. 그렇지 않으면 체인의 첫 번째 함수는 마지막 함수가 끝날 때까지 기다려야 합니다.Python을 사용하면 다음과 같습니다.

    try:
            requests.get("http://secondAzureFunction.com/api/",timeout=0.0000000001)
    except requests.exceptions.ReadTimeout: 
            pass
    

하지만 그것은 나에게 약간 진부해 보입니다.

  1. Azure 스토리지 큐를 사용합니다.첫 번째 기능은 다른 Azure 기능을 트리거하는 대기열로 메시지를 전달합니다.그것이 더 우아한 해결책인 것 같습니다.Fabio는 다음과 같이 쓰고 있습니다.

이를 통해 프로비저닝, 확장 및 장애 처리를 위한 모든 논리를 활용하는 동시에 기능을 작고 빠르고 분리할 수 있습니다.

한 함수 앱을 다른 함수 앱으로 호출할 수 없습니다(즉, 완전한 URL이 없는 다른 http 트리거로 Http 트리거).

우리가 다른 코딩 방법으로 달성할 수 있는 것과 같습니다.

[FunctionName("CreateUser")]
    public Task<IActionResult> CreateUser([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "put", Route = "{apiName}")] HttpRequest req, ILogger log, string apiName)
    {
        log.LogInformation("Requested API => " + apiName);
        CreateUser();
        // Based on condition you can call the internal methods 
        return Task.FromResult(" CreateUser-response");
    }
    [FunctionName("FetchUser")]
    public Task<IActionResult> FetchUser([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "put", Route = "{apiName}")] HttpRequest req, ILogger log, string apiName)
    {
        log.LogInformation("Requested API => " + apiName);
        FetchUser();
        // Based on condition you can call the internal methods 
        return Task.FromResult("FetchUser-response");
    }
    [FunctionName("ProcessUser")]
    public Task<IActionResult> ProcessUser([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", "put", Route = "{apiName}")] HttpRequest req, ILogger log, string apiName)
    {
        log.LogInformation("Requested API => " + apiName);
        ProcessUser();
        // Based on condition you can call the internal methods 
        return Task.FromResult("FetchUser-response");
    }
    private void CreateUser()
    {
        // Create User Logic
    }
    private void FetchUser()
    {
        // Fetch User Logic
    }
    private void ProcessUser()
    {
        // Process User Logic
    }

아마도 이것은 API 끝점을 호출하는 Azure 함수 타이머 트리거를 만드는 방법을 가진 누군가에게 도움이 될 것입니다.

그것은 꽤 간단합니다.

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using RestSharp;

namespace FunctionApp1
{
   public class Function1
   {
       public const string baseurl = "https://localhost:5101/api/v1";
       public const string ApiKey = "remoteAPiKey";

       [FunctionName("TestFunction")]
       public void Run([TimerTrigger("*/5 * * * *")]TimerInfo myTimer, ILogger log)
       {
           string url = $"{baseurl}/Values";
           var client = new RestClient(url);
           var request = new RestRequest();
           request.Method = Method.Get;
           request.AddHeader("ApiKey", ApiKey);
           RestResponse response = client.Execute(request);
           log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
       }
   }
}

자세한 내용은 여기에서도 확인할 수 있습니다.

언급URL : https://stackoverflow.com/questions/46315734/how-to-call-another-function-with-in-an-azure-function

반응형