Azure函数[JavaScript/Node.js]-HTTP调用,良好做法 [英] Azure Functions [JavaScript / Node.js] - HTTP call, good practices

查看:65
本文介绍了Azure函数[JavaScript/Node.js]-HTTP调用,良好做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

From my Azure Function (which runs in Node.js, triggered by EventHub message) I would like to make a post request to some external page. Something like:

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

上面的代码可能会起作用,但是我怀疑那是否不是反模式.

The code above will probably work but I have a doubt if that is not an antipattern.

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

Imagine situation when there are thousands of functions triggered in short period of time - for each execution we would need to create an HTTP client and create a connection...

从简短的研究中,我发现了一些针对C#Azure函数的解决方案建议:

From short research I have found some solution proposal for C# Azure Functions: https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/ which uses static HttpClient class.

我有一个问题,Node.js Azure函数中是否有任何类似的方法?还是通过其他方法来避免此问题,以便在Node.js Azure函数执行之间共享对象?

I have a question, is there any similar approach in Node.js Azure Function? Or any other way to avoid this problem, to share an object between Node.js Azure Function executions?

推荐答案

如果成千上万的函数在短时间内触发,则应通过修改 http.globalAgent 或传递实例来限制套接字新的代理商

If thousands of functions triggered in short period of time you should limit the sockets by modifying the http.globalAgent or by passing an instance of a new Agent

代理负责管理连接的持久性和重用适用于HTTP客户端.它维护一个给定的未决请求队列主机和端口,对每个主机和端口重复使用一个套接字连接,直到队列为空,此时套接字被销毁或放置放入一个池中,该池将再次用于向同一池中的请求主机和端口.它是被销毁还是被池化取决于keepAlive选项.

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以启用池连接.

http.globalAgent.maxSockets defaults to infinity so unless you limit this value your function will run out of sockets and you'll see your requests start to fail. Additionally if you are planning on connecting to the same host you should enable keep-alive on the globalAgent/Agent to enable pooled connections.

这篇关于Azure函数[JavaScript/Node.js]-HTTP调用,良好做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆