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

标签 javascript node.js azure azure-functions

从我的 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/

相关文章:

javascript - 从标记中的 href 获取查询字符串参数

azure - 如何在新门户Azure中的Azure Active Directory中为自己授予权限?按钮 "Grant Permission"丢失

javascript - 滚动时在元素上覆盖固定标题

asp.net - 有没有人使用 ASP.net (webforms) 来动态生成 javascript 和/或 css 文件?

javascript - 在node js中对数据进行签名并在Java中进行验证

javascript - 如何在 TypeScript 中导出对象?

sql - Azure SQL Server "clr strict security"可以更改吗

c# - Azure:启动远程调试器失败

javascript - 在 Qualtrics 中使用 javascript 将可拖动条设置为自定义开始位置

node.js - 通过 chatGpt api 流从 NextJs (express) 返回 ReadableStream