How to communicate Web and Worker dynos with Node.js on Heroku?

后端 未结 2 500
南笙
南笙 2020-12-12 22:34

Web Dynos can handle HTTP Requests

and while Web Dynos handles them Worker Dynos can handle jobs from it.

2条回答
  •  渐次进展
    2020-12-12 23:05

    From what I can tell, Heroku does not supply a way of communicating for you, so you will have to build that yourself. In order to communicate to another process using Node, you will probably have to deal with the process' stdin/out/err manually, something like this:

    var attachToProcess = function(pid) {
        return {
            stdin: fs.createWriteStream('/proc/' + pid + '/fd/0'),
            stdout: fs.createReadStream('/proc/' + pid + '/fd/1'),
            stderr: fs.createReadStream('/proc/' + pid + '/fd/2')
        };
    };
    
    var pid = fs.readFile('/path/to/worker.pid', 'utf8', function(err, pid) {
        if (err) {throw err;}
        var worker = attachToProcess(Number(pid));
        worker.stdin.write(...);
    });
    

    Then, in your worker process, you will have to store the pid in that pid file:

    fs.writeFile('/path/to/worker.pid', process.pid, function(err) {
        if (err) {throw err;}
    });
    

    I haven't actually tested any of this, so it will likely take some working and building on it, but I think the basic idea is clear.

    Edit

    I just noticed that you tagged this with "redis" as well, and thought I should add that you can also use redis pub/sub to communicate between your various processes as explained in the node_redis readme.

提交回复
热议问题