进程间通信

Pandora.js 提供了一个进程间对象代理的功能,可以方便的实现跨进程访问、调用。

直接发布对象和获取对象代理

看下面的例子:

  1. const {getProxy, publishObject} = require('dorapan');
  2. async function main() {
  3. // 发布 Math 到 IPC-Hub
  4. await publishObject('math', Math);
  5. // 获得对象代理
  6. const proxy = await getProxy('math');
  7. // 所有方法直接 await 调用
  8. const val = await proxy.abs(-1234);
  9. console.log(val);
  10. }
  11. main().catch(console.error);

Service 使用 IPC-Hub

Pandora.js 提供了进程间的对象代理功能,Service 可以便捷的发布到 IPC-Hub 中。

procfile.js

  1. module.exports = function (pandora) {
  2. // 定义两个进程
  3. pandora
  4. .process('a')
  5. .scale(1);
  6. pandora
  7. .process('b')
  8. .scale(1);
  9. // 定义两个 Service
  10. // (该例子 Service 实现全部写在 procfile.js 中了,这不是一个好的实践)
  11. class ServiceA {
  12. async getPid() {
  13. return process.pid;
  14. }
  15. }
  16. class ServiceB {
  17. constructor(context) {
  18. this.context = context;
  19. }
  20. async start() {
  21. // 或者 require('dorapan').getProxy();
  22. const serviceA = await this.context.getProxy('serviceA');
  23. const pid = await serviceA.getPid();
  24. console.log();
  25. console.log();
  26. console.log('pid from serviceA', pid);
  27. console.log('pid from self', process.pid);
  28. console.log();
  29. console.log();
  30. }
  31. }
  32. // 定义 ServiceA 在 进程 a
  33. pandora
  34. .service('serviceA', ServiceA)
  35. .process('a')
  36. // 标识 serviceA 发布到 IPC-Hub 中
  37. .publish();
  38. // 定义 ServiceB 在进程 b
  39. pandora
  40. .service('serviceB', ServiceB)
  41. .process('b');
  42. }

获得 IPC-Hub 整体对象

IPC-Hub 还有一些别的能力,可以通过 require('dorapan').getHub() 获得。

具体参考 pandora-hub 包下的 Facade 类的 API