在Heroku的免费应用程序中,dyno似乎一直在空转——我的应用程序流量很低,但在我的情况下,我的用户不得不等待20多秒才能启动一个新的dyno,这也是不能接受的。

坦率地说,在这样的等待下,许多人甚至在第一页显示之前就离开了。

所以,我遇到了一个问题:当我每天的流量都在个位数时,我是否应该每月支付36美元来为每个用户节省令人尴尬的漫长20秒?

有没有办法解决这个问题?


当前回答

如果你正在使用带有express的nodejs,你可以添加一个每10分钟调用一次自己的端点。

路由器:

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 }

其他回答

在一个spring应用程序中,每2分钟向根url路径发出一个HTTP请求 `

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

public class HerokuNotIdle {

private static final Logger LOG = LoggerFactory.getLogger(HerokuNotIdle.class);

@Scheduled(fixedDelay=120000)
public void herokuNotIdle(){
    LOG.debug("Heroku not idle execution");
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getForObject("http://yourapp.herokuapp.com/", Object.class);
}
}

记住,配置上下文以启用调度器并为调度器创建bean

@EnableScheduling
public class AppConfig {

@Bean
public HerokuNotIdle herokuNotIdle(){
    return new HerokuNotIdle();
}
}

你也可以试试http://kaffeine.herokuapp.com(由我制作),它是为了防止Heroku应用程序进入睡眠。它将每10分钟ping你的应用程序,所以你的应用程序不会进入睡眠状态。完全免费。

我认为最简单的解决方法是每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

我使用的Heroku调度插件由Heroku免费提供。一旦添加,它就像创建一个带有“curl http://yourapp.herokuapp.com”和10分钟间隔的作业一样简单。

伙计,这是一个你可以运行的英雄应用程序,让多个英雄应用程序存活下来。只需在config.json中添加你想要ping的url。

https://github.com/jcarras/rise-and-shine