How to call another function with in an Azure function

前端 未结 6 825
醉话见心
醉话见心 2021-02-07 00:21

I have written 3 functions as follows

  1. create users in db
  2. fetch users from db
  3. process users

In [3] function, I will call [2] functi

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 01:09

    You can do it directly by calling the 2nd function as a normal C# static method.

    But in this case you lose benefits of Azure Functions scaling and distributing (for example, based on server load your 2nd function may be called from different part of the world).

    1. Send an HTTP request to another function's public URL
    2. Put a message into an Azure Queue and let the other Azure Function process it
    3. Use Durable Functions

    As for the 1st option in C# you can do it like so:

        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();
        }
    

    Also sometimes you need your first Azure Function to return HTTP response first, and then do something in the background, so this solution won't work. In this case options 2 and 3 are suitable.

提交回复
热议问题