在Heroku的免费应用程序中,动态资源似乎会保持空闲状态 - 我的应用程序流量非常低,但是对于我的用户需要等待20多秒才能启动新的动态资源来说,这也不是真正可接受的情况。
坦白地说,在那种等待时间下,许多人甚至会在第一页显示之前就离开。
所以,我有一个问题:当我的流量每天只有个位数时,我是否应该支付36美元/月来节省每个用户尴尬的长达20秒的等待时间呢?
有没有办法解决这个问题?
在Heroku的免费应用程序中,动态资源似乎会保持空闲状态 - 我的应用程序流量非常低,但是对于我的用户需要等待20多秒才能启动新的动态资源来说,这也不是真正可接受的情况。
坦白地说,在那种等待时间下,许多人甚至会在第一页显示之前就离开。
所以,我有一个问题:当我的流量每天只有个位数时,我是否应该支付36美元/月来节省每个用户尴尬的长达20秒的等待时间呢?
有没有办法解决这个问题?
我认为最简单的解决方法是每30分钟自己ping一下自己的服务器。以下是我在Node.js项目中使用的代码,以防止休眠。
const request = require('request');
const ping = () => request('https://<my-app-name>.herokuapp.com/', (error, response, body) => {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print body of response received
});
setInterval(ping, 20*60*1000); // I have set to 20 mins interval
另一种可行的解决方案:wokeDyno 这是一个博客文章,介绍了它的工作原理: 在应用程序中集成它非常容易:
/* Example: as used with an Express app */
const express = require("express")
const wakeDyno = require("woke-dyno");
// create an Express app
const app = express();
// start the server, then call wokeDyno(url).start()
app.listen(PORT, () => {
wakeDyno(DYNO_URL).start(); // DYNO_URL should be the url of your Heroku app
});
app.get("/keep-alive",require("path/to/keepAlive.js").keepAlive);
keepAlive.js
let interval;
function keepAlive(req, res) {
if(interval) return res.end();
interval = setInterval(() => {
fetch("http://your-heroku-subdomain/keep-alive")
.catch(err => {/*handle error here*/});
}
,60_000);
return res.end();
}
module.exports = { keepAlive }