我有一个nodejs应用程序,监听正在对它进行的休息调用。然而,我想给我的代码添加一些智能。
例如,我只想每5分钟执行一次给定调用的函数。因此,即使有人每秒钟或每分钟调用rest链接,我也只想每5分钟执行一次。我如何实现这种灵活性?
随机调用nodejs服务器
http:// abc.com/pager/a is called 100 times within 5 minutes should only execute the function once for the first call and must resume executing the function after 5 minutes
http:// abc.com/pager/b
http:// abc.com/pager/c
示例代码app.post('/pager/:room',function(req,res){
var room = req.params.room;
if( room == 'a'){
console.log("Room A called");
//execute function once every 5 minutes only for room a
func1(room)
}
else if( room == 'b'){
console.log("Room B called");
//execute function once every 5 minutes only for room b
func1(room)
}
else if( room == 'c'){
console.log("Room C called");
//execute function once every 5 minutes only for room c
func1(room)
}
});
这是一个泛型函数,返回另一个函数,该函数在被调用后在指定的毫秒数内禁用自己。
function tempDisableAfterCall(fn, ms) {
var timeToReset = 0;
return function() {
var currentTime = new Date().getTime();
if (currentTime < timeToReset) {
return;
} else {
timeToReset = currentTime + ms;
fn.apply(this, arguments);
}
}
}
// Function that will be temporarily disabled
function printNumber(num) {
console.log(num)
}
// Create a modified function that is disabled after it has been called
var printNumberWait = tempDisableAfterCall(printNumber, 5000);
// Call the function every 500 ms, but you will only see a log every 5 seconds
setInterval(function() {
printNumberWait(new Date().getTime());
}, 500)
这是一个基本的例子,说明无论端点被调用的频率如何,您都可以实现每5分钟只运行一次函数。
app.set('roomFunctionActive', false);
app.post('/pager/:room',function(req,res){
var room = req.params.room;
var roomFunctionActive = app.get('roomFunctionActive');
if(!roomFunctionActive) {
app.set('roomFunctionActive', true);
func1(room);
setTimeout(function() {
app.set('roomFunctionActive', false);
}, 300000);
}
});
当然,roomFunctionActive可以更改为每个房间('a', 'b', 'c')的不同变量,允许每个房间的函数每5分钟运行一次。
一个redis实例将是一个很好的解决方案,你可以设置一个键值对,并设置它在5分钟后过期。
检查键值对是否存在,如果不存在,则执行函数并设置一个新的键值对,有效期为5分钟。
这可能有点过分,但你甚至可以使用一个名为rediss -sessions的模块来创建有时间限制的令牌,特别是对于这种目的
https://www.npmjs.com/package/redis-sessions