Created
September 6, 2012 13:56
-
-
Save ryan-roemer/3656510 to your computer and use it in GitHub Desktop.
Node.js v0.8 Cluster Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cluster = require "cluster" | |
log = require "winston" | |
config = require "config" # Your configuration goes here. | |
app = require "./server" # Your real server goes here. | |
numCpus = require("os").cpus().length | |
workers = {} | |
# Helpers. | |
shutdown = -> | |
log.warning "Hard shutdown." | |
for own pid, worker of workers | |
log.warning "Killing worker: #{pid}" | |
worker.process.kill() | |
process.exit 0 | |
# Start up the cluster. | |
if cluster.isMaster | |
# Fork workers. | |
cluster.fork() for cpu in [0...numCpus] | |
cluster.on "online", (worker) -> | |
workers[worker.process.pid] = worker | |
log.info "[#{worker.id}] Worker #{worker.process.pid} came up." | |
cluster.on "exit", (worker, code, signal) -> | |
log.warning "[#{worker.id}] Worker #{worker.process.pid} died. Restarting." | |
delete workers[worker.process.pid] | |
cluster.fork() | |
# Manually shutdown workers on signals. | |
process.on signal, shutdown for signal in ["SIGINT", "SIGQUIT", "SIGTERM"] | |
log.info "Master #{process.pid} started." | |
else | |
# Worker: Start server and message "up". | |
app.listen config.app.port, config.app.addr | |
log.info "Worker #{process.pid} started." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment