在 Node.js 中,如何让一个服务器调用另一个服务器上的函数

In Node.js, how do I make one server call a function on another server?

本文关键字:服务器 一个 调用 另一个 函数 js Node      更新时间:2023-09-26

假设我有 2 台 Web 服务器。他们俩都刚刚安装了Node.js并且正在运行一个网站(使用Express)。 非常基本的东西。

服务器 A 如何告诉服务器 B 执行函数?(节点内.js)

宁愿。。。有没有一个 npm 模块让我很容易?

服务器 A 如何告诉服务器 B 执行函数?

您可以使用其中一个 RPC 模块,例如 dnode。

查看通配符API,它是JavaScript的RPC实现。

它在浏览器和 Node.js 服务器之间工作,也可以在多个 Node.js 进程之间工作:

// Node.js process 1
const express = require('express');
const wildcardMiddleware = require('@wildcard-api/server/express');
const {endpoints} = require('@wildcard-api/server');
endpoints.hello = async function() {
  const msg = 'Hello from process 1';
  return msg;
};
const app = express();
app.use(wildcardMiddleware());
app.listen(3000);
// Node.js process 2
const wildcard = require('@wildcard-api/client');
const {endpoints} = require('@wildcard-api/client');
wildcard.serverUrl = 'http://localhost:3000';
(async () => {
  const msg = await endpoints.hello();
  console.log(msg); // Prints "Hello from process 1"
})();

您可以在此处浏览示例的代码。

你很可能想要一个像 Node 的 JSON-RPC 模块这样的东西。经过一些快速搜索,这里有一个用于Connect的JSON-RPC中间件模块,非常适合与Express一起使用。

此外,这个看起来也很有前途。

更新:我在下面制作和链接的库目前没有维护。请查看此线程上的其他答案。

<小时 />

您需要的称为 RPC。可以构建自己的,但根据您需要的功能,这可能很耗时。

考虑到我必须投入的时间,我建议找到一个适合您目的的体面库,而不是手卷。我的用例需要额外的复杂功能,例如选择性 RPC 调用,我找不到足够轻量级的东西,所以不得不自己推出。

这是 https://github.com/DhavalW/octopus。

相关文章: