gpt4 book ai didi

javascript - Azure Functions [JavaScript/Node.js] - HTTP 调用,良好实践

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:31 25 4
gpt4 key购买 nike

从我的 Azure 函数(在 Node.js 中运行,由 EventHub 消息触发)中,我想向某个外部页面发出发布请求。像这样的东西:

module.exports = function (context, eventHubMessages) {

var http = require("http");

context.log('JavaScript Function triggered by eventHub messages ');

http.request(post_options, function(res){
...
})

context.done();

上面的代码可能会工作,但我怀疑这是否不是反模式。

想象一下在短时间内触发数千个函数的情况 - 对于每次执行,我们都需要创建一个 HTTP 客户端并创建一个连接...

通过简短的研究,我发现了一些针对 C# Azure Functions 的解决方案建议:https://learn.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/它使用静态 HttpClient 类。

我有一个问题,Node.js Azure Function 中是否有类似的方法?或者有任何其他方法可以避免此问题,在 Node.js Azure Function 执行之间共享对象?

最佳答案

如果在短时间内触发了数千个函数,您应该通过修改 http.globalAgent 或传递新 Agent 的实例来限制套接字。

An Agent is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on the keepAlive option.

来源:https://nodejs.org/api/http.html#http_class_http_agent

http.globalAgent.maxSockets 默认为无穷大,因此除非您限制此值,否则您的函数将耗尽套接字,并且您将看到您的请求开始失败。此外,如果您计划连接到同一主机,则应在 globalAgent/Agent 上启用 keep-alive 以启用池连接。

关于javascript - Azure Functions [JavaScript/Node.js] - HTTP 调用,良好实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com