dispatch.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*!
  2. * graceful - example/connect_with_cluster/dispatch.js
  3. * Copyright(c) 2013 fengmk2 <fengmk2@gmail.com>
  4. * MIT Licensed
  5. */
  6. "use strict";
  7. /**
  8. * Module dependencies.
  9. */
  10. // http://nodejs.org/docs/latest/api/domain.html#domain_warning_don_t_ignore_errors
  11. var cluster = require('cluster');
  12. var path = require('path');
  13. cluster.setupMaster({
  14. exec: path.join(__dirname, 'worker.js')
  15. });
  16. // In real life, you'd probably use more than just 2 workers,
  17. // and perhaps not put the master and worker in the same file.
  18. //
  19. // You can also of course get a bit fancier about logging, and
  20. // implement whatever custom logic you need to prevent DoS
  21. // attacks and other bad behavior.
  22. //
  23. // See the options in the cluster documentation.
  24. //
  25. // The important thing is that the master does very little,
  26. // increasing our resilience to unexpected errors.
  27. cluster.fork();
  28. cluster.fork();
  29. // when worker disconnect, fork a new one
  30. cluster.on('disconnect', function (worker) {
  31. var w = cluster.fork();
  32. console.error('[%s] [master:%s] wroker:%s disconnect! new worker:%s fork',
  33. new Date(), process.pid, worker.process.pid, w.process.pid);
  34. });
  35. // if you do not want every disconnect fork a new worker.
  36. // you can listen worker's message.
  37. // graceful will send `graceful:disconnect` message when disconnect.
  38. // cluster.on('fork', function(worker) {
  39. // worker.on('message', function (msg) {
  40. // if (msg === 'graceful:disconnect') {
  41. // var w = cluster.fork();
  42. // console.error('[%s] [master:%s] wroker:%s disconnect! new worker:%s fork',
  43. // new Date(), process.pid, worker.process.pid, w.process.pid);
  44. // }
  45. // });
  46. // });
  47. cluster.on('exit', function (worker) {
  48. console.error('[%s] [master:%s] wroker:%s exit!',
  49. new Date(), process.pid, worker.process.pid);
  50. });