【问题标题】:Azure function: limit the number of calls per secondAzure 功能:限制每秒调用次数
【发布时间】:2018-08-26 16:06:36
【问题描述】:

我有一个由队列消息触发的 Azure 函数。该函数向第三方 API 发出请求。不幸的是,这个 API 有限制 - 每秒 10 个事务,但我在服务总线队列中每秒可能有超过 10 条消息。如何限制 Azure 函数的调用次数以满足第三方 API 限制?

【问题讨论】:

  • 已经回答here。限制 ATM 没有什么好故事。

标签: c# azure azure-functions azureservicebus throttling


【解决方案1】:

不幸的是,没有内置选项。

限制并发执行的唯一可靠方法是在固定的应用服务计划(不是消耗计划)上运行,始终只运行 1 个实例。您必须为此实例付费。

然后在host.json文件中设置选项:

"serviceBus": {
    // The maximum number of concurrent calls to the callback the message
    // pump should initiate. The default is 16.
    "maxConcurrentCalls": 10
}

最后,确保您的函数需要一秒钟来执行(或其他最短持续时间,并相应地调整并发调用)。

正如@SeanFeldman 所建议的,请参阅this answer 中的一些其他想法。它是关于存储队列的,但也适用于服务总线。

【讨论】:

    【解决方案2】:

    您可以尝试编写一些自定义逻辑,即在 Azure 函数中实现您自己的内存队列来排队请求并限制对第三方 API 的调用。无论如何,在调用第三方 API 成功之前,您不需要确认队列中的消息。这样一来,可靠性也得以保持。

    【讨论】:

    • 这违背了函数的模型。这样就可以更轻松地编写自定义服务总线消费者应用程序了。
    【解决方案3】:

    保持系统完整性的最佳方法是限制服务总线消息的消耗。您可以控制 QueueClient 处理消息的方式,请参阅:https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues#4-receive-messages-from-the-queue

    查看“最大并发调用数”

     static void RegisterOnMessageHandlerAndReceiveMessages()
    {
        // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
        var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
        {
            // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
            // Set it according to how many messages the application wants to process in parallel.
            MaxConcurrentCalls = 1,
    
            // Indicates whether the message pump should automatically complete the messages after returning from user callback.
            // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync().
            AutoComplete = false
        };
    
        // Register the function that processes messages.
        queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
    }
    

    【讨论】:

    • 无法直接访问 Azure Functions 中的 QueueClient
    【解决方案4】:

    您想摆脱在第二个时间间隔内收到的 N-10 条消息,还是希望根据 API 限制来处理每条消息?对于后者,您可以将您的函数处理的消息添加到另一个队列中,您可以每秒通过另一个函数(计时器触发器)从中读取一批 10 条消息

    【讨论】:

    • 这并不一定保证限制。如果在第 1 秒调用很慢并且只处理了 5 个请求,则第二个函数可能会在第 2 秒收到 5+10 个请求。
    • 第二个函数(由计时器触发)决定它读取多少消息(批量大小或应用逻辑)
    猜你喜欢
    • 2017-05-19
    • 2012-02-14
    • 1970-01-01
    • 2011-08-27
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多