在子进程之间共享一个模块导入

Share one module import among child processes

当我尝试使用 Discord.js 在我的 Discord 机器人上进行分片时出现了这个问题。每个分片(至少在 process 模式下)都有自己的程序在执行,这意味着不同的分片实际上是独立的机器人。我的机器人的一项功能要求用户在服务器和 DM 中使用命令。问题是所有 DM 都被发送到单个分片,因此来自不同分片上的服务器的任何用户都会看到命令似乎已损坏,因为虽然服务器的分片正确地跟踪所有内容,但带有 DM 的分片正在跟踪一个不同的服务器组,看不到任何数据。

我对分片相当陌生,我认为解决这个问题的最好方法是处理我在导入到 index.js 的模块中跟踪的所有信息,然后导入必要的部分进入每个 bot.js 子进程分片,因此所有数据都整合到一个地方,每个分片都可以访问它。但是,无论我如何设置,当我尝试将信息从 index.js(分片管理器)导入到 bot.js(机器人代码 运行 在每个分片上)。

这一定是对子进程和父进程之间导入的某种限制,但我还没有找到任何相关信息。有谁知道如何让导入在这里正常工作,或者允许集中信息处理以便每个分片都可以访问它的不同方法?

That's what I was doing originally, which gives each child process its own set of information to work with. I don't think I was clear in the question, but this is information and data being created in real time, so each process would have completely different sets of data because they're handling different servers. What I need is some way to keep track of this across all child processes so they all have access to the same information and can all manipulate said information.

那么你要做的就是使用client.shard.broadcastEval()。您可以使用以下方法从所有客户端缓存中获取公会 属性:

const getServer = async (guildID) => {
    // try to get guild from all the shards
    const req = await client.shard.broadcastEval(`this.guilds.cache.get("${guildID}")`);

    // return Guild or null if not found
    return req.find(res => !!res) || null;
}

Example by ZiNc#2032
在这些链接中阅读有关分片的更多信息: