Node.js 使用knex插入数据时CPU使用率高(300%)
我想通过knex向SQL Server插入大量数据。我已经降低了一次插入的数量和插入的并发性,但最终仍然会导致高CPU使用率。它是否可以在knex启动每个插件的连接时使用它?如有任何意见,将不胜感激。 这是我用来连接数据库的代码Node.js 使用knex插入数据时CPU使用率高(300%),node.js,sql-server,knex.js,Node.js,Sql Server,Knex.js,我想通过knex向SQL Server插入大量数据。我已经降低了一次插入的数量和插入的并发性,但最终仍然会导致高CPU使用率。它是否可以在knex启动每个插件的连接时使用它?如有任何意见,将不胜感激。 这是我用来连接数据库的代码 client: "mssql", connection: { server: productionDbIp, user: productionDbUsername, password: productionDbPassword
client: "mssql",
connection: {
server: productionDbIp,
user: productionDbUsername,
password: productionDbPassword,
database: productionDbName,
options: {
port: productionDbPort
},
pool: { min: 0, max: 7 }
}
下面是用于调整插入的代码
const insertQue = new PQueue({ concurrency: 1 });
// format inserts returns an array of objects that are ready to be inserted
const [inserts] = await formatInserts(distinctData);
const insertPromises = [];
while (inserts.length > 0) {
const insert = inserts.splice(0,10);
try {
insertPromises.push(
insertQue.add(() => insertToDb(insert, 'tableName'))
);
} catch (error) {
console.log(error);
}
}
try {
await Promise.all(insertPromises);
} catch (error) {
console.log(error);
}
}
async function insertToDb(data, table, numTry = 0) {
try {
return await knex(table).insert(data);
} catch (error) {
if (numTry > 3) {
console.log(error);
throw { message: `Error inserting data`, data };
}
return insertToDb(data, numTry + 1);
}
}
一个快速的谷歌搜索显示了这个答案
因此,拥有300%甚至可能不是问题。你的虚拟核心正在准备完成他们的工作。因为您使用的是异步调用,所以多个进程可以一起工作。我对knex一无所知,但您是否尝试过调用存储进程而不是直接DB insert?没有,我没有尝试过。我会调查的谢谢Hanks,我想这就是发生的事情Hello@ConnorRobertson请标记答案以结束你的问题:这将清理StackOverflow,并在问下一个问题时帮助你。