使分片进程使用同一个池

问题描述 投票:0回答:1

我想在我的分片管理器 (server.js) 中创建一个池并将其传递给分片进程 (bot.js)。这是我的分片管理器(server.js):

var clientMysqlEvent = require('./database/botpool.js').connection;
const flatted = require('flatted');
const clientMysqlEventserialized = flatted.stringify(clientMysqlEvent);
const { ShardingManager } = require('discord.js');
  const shard = new ShardingManager('./bot.js', {
    token: config.token,
    respawn: true,
  });
  shard.spawn({ amount: splen, delay: 100, timeout: 120000 }); 
    //console.log(`[DEBUG/SHARD] Shard ${shard.id} connected to Discord's Gateway.`)
    // Sending the data to the shard.
    shard.on("ready", () => {
      console.log(`[SHARD] Shard ${formatedShardId} connected to Discord's Gateway.`)
      // Sending the data to the shard.
      shard.send({type: "shardId", data: {shardId: shard.id, shardTotal: splen}});
      shard.send({type: "myDb", data: {dbManager: clientMysqlEventserialized}});
});

botpool.js:

const mysql  = require('mysql');
    var connection = mysql.createPool({
      connectionLimit : 20,
      host     : 'localhost',
      user     : 'user',
      password : 'pass',
      database : 'db'
    });
    connection.on('release', function (connection1) {
        console.log('BOT: Connection %d released', connection1.threadId);
      });
    connection.on('acquire', function (connection1) {
        console.log('BOT: Connection %d acquired', connection1.threadId);
      });
    connection.on('connection', function (connection1) {
        console.log('BOT: Connection %d connected', connection1.threadId);
      });
    connection.on('enqueue', function () {
        console.log('BOT: Waiting for available connection slot');
      });
    exports.connection = connection;

分片流程(bot.js):

const flatted = require('flatted');
var mysql = null;
process.on('message', message => {
  if (!message.type) return false;
  if (message.type == "shardId") {
    console.log(`The shard id is: ${message.data.shardId + Number(1)}`);
    console.log(`Total shard number is: ${message.data.shardTotal}`)
    clientShardId = message.data.shardId + Number(1)
    totalShardIds = message.data.shardTotal
    console.log("Captured data: "+clientShardId+"/"+totalShardIds)
    client.user.setPresence({ activities: [{ name: `${config.activities} [${message.data.shardId + Number(1)} / ${message.data.shardTotal}]` }] });
} else if (message.type == "myDb") {
    //mysql = message.data.dbManager;
    mysql = flatted.parse(message.data.dbManager);
    //console.log("mysql:")
    //console.log(mysql)
};
})

遗憾的是,这种方法并没有达到我想要的效果,并且分片进程(bot.js)创建了自己的池。

mysql node.js discord.js sharding
1个回答
0
投票

让我尝试解决您的问题,但我无法确认它是否正确。 您的方法不起作用的原因是您正在分片管理器中创建池连接,然后尝试将连接对象发送到分片进程。但是,连接对象无法序列化并通过 IPC 通道发送。

根据以上观点,你可以尝试:

  1. 在分片进程 (bot.js) 而不是分片管理器 (server.js) 中创建池连接。
  2. 将数据库连接配置(如主机、用户、密码、数据库名称)发送给分片进程。
  3. 使用分片进程中的数据库连接配置来创建池连接。
© www.soinside.com 2019 - 2024. All rights reserved.