手动触发Azure函数-时间触发

vuktfyat  于 2023-05-01  发布在  其他
关注(0)|答案(3)|浏览(115)

我有一个Azure函数,每周在定时器触发器上运行一次。这工作得很好,正如预期的那样,但是大约每个月有一两次,用户需要根据请求运行此函数,所以我需要对该函数进行发布以触发它-就像您可以从Azure门户中执行的那样。
查看Azure门户,正在对函数执行http post请求,如下所示:

https://{funcapp}.azurewebsites.net/admin/functions/{func}

但是,如果我从Postman执行此操作,我会得到一个Http 401响应。我该如何去做这个请求呢?
我有一个选择,宁愿将触发器更改为队列,并每周运行第二个函数,以向队列添加消息,但这对我来说似乎有点过分。

xu3bshqb

xu3bshqb1#

如果你想调用admin API来触发你的定时器函数,你需要在你的请求中添加你的函数主密钥,否则你会得到401 Unauthorized。
在函数应用设置面板〉主机密钥(所有函数)〉_master中找到它。
将其添加到请求头x-functions-key:<masterkey>中。
请注意,在此帖子请求admin API中,您需要发送一个application/json类型主体(至少包含一个空的json {}),此格式是必需的,否则您可能会得到415 Unsupported Media Type。
如果这个帖子请求是由用户执行的,并且你不希望主密钥暴露给他们,我建议你使用@玛丽提供的解决方案,尝试一下,你可能会发现它并不像你想象的那么过分。

nqwrtyyt

nqwrtyyt2#

如果您利用单个函数应用程序可以由多个函数组成的事实来在函数之间共享业务逻辑,会怎样呢?你可以有一个功能。json触发器基于HTTP请求,另一个触发器基于计时器。
您的函数应用程序架构可能如下所示:

MyFunctionApp
|     host.json
|____ shared
|     |____ businessLogic.js
|____ function1
|     |____ index.js
|     |____ function.json
|____ function2
      |____ index.js
      |____ function.json

在“function 1/index.js”和“function 2/index。js”

var logic = require("../shared/businessLogic");

module.exports = logic;

功能。function 1和function 2的json可以被配置为不同的触发器(定时器和HTTP或队列)。...随你便!).

在“shared/businessLogic中。js

module.exports = function (context, req) {
    // This is where shared code goes. As an example, for an HTTP trigger:
    context.res = {
        body: "<b>Hello World</b>",
        status: 201,
        headers: {
            'content-type': "text/html"
        }
    };     
    context.done();
};

(This是一个JavaScript的例子,但同样适用于其他语言!)

3lxsmp7m

3lxsmp7m3#

这是给予一个公认的答案的例子。在下面的示例函数应用程序中,有两个函数:TimerTrigger和HTTPTrigger。请注意,默认名称“Run”已更改,因此函数具有不同的名称。
运行此命令时,计时器和http触发器将处于活动状态。在实际的应用程序中,它们将调用相同的业务逻辑。

public class Host
    {
        [FunctionName("OnTimerFired")]
        public void RunTimer([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }

        [FunctionName("OnHttpTrigger")]
        public static async Task<IActionResult> RunHttpTrigger(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }

    }

相关问题