我有一个 MySQL 服务器(版本 8.0.35-0ubuntu0.20.04.1),并且希望从 Node.js 应用程序监视特定 MySQL 表中的 UPDATE 和 INSERT 操作。这些更改应该来自任何地方,而不仅仅是 Node.js 应用程序本身。
我找到了一些关于旧 NPM 包的文档,名为 @rodrigogs/mysql-events。
当尝试实现此包的文档中的示例代码时,我收到以下错误:
ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
我知道每个MySQL用户都有一定的身份验证方法。我尝试了以下两种方法,但没有效果:
知道如何克服这个问题吗?
是否有更好的解决方案,也许让 MySQL 触发器触发并将必要的信号发送到 Node.js 应用程序或处理二进制日志监控的较新 Node.js 包?
谢谢你。
我执行了以下步骤,它对我来说效果很好。
CREATE USER 'test_native_user'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test_native_password';
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'test_native_user'@'localhost';
GRANT SELECT ON test.* TO 'test_native_user'@'localhost';
npm install --save mysql @rodrigogs/mysql-events
test.articles
表的事件:const mysql = require('mysql');
const MySQLEvents = require('@rodrigogs/mysql-events');
const program = async () => {
const connection = mysql.createConnection({
host: 'localhost',
user: 'test_native_user',
password: 'test_native_password'
});
const instance = new MySQLEvents(connection, {
startAtEnd: true,
includeSchema: {
'test': ['articles']
}
});
await instance.start();
instance.addTrigger({
name: 'TEST',
expression: '*',
statement: MySQLEvents.STATEMENTS.ALL,
onEvent: (event) => { // You will receive the events here
console.log(event);
}
});
instance.on(MySQLEvents.EVENTS.CONNECTION_ERROR, console.error);
instance.on(MySQLEvents.EVENTS.ZONGJI_ERROR, console.error);
};
program()
.then(() => console.log('Waiting for database events...'))
.catch(console.error);
针对
test.articles
表运行以下三个查询:
INSERT INTO articles VALUES (7, 2, 'subject 7', 'content 7');
UPDATE articles SET subject = 'subject 77' WHERE id = 7;
DELETE FROM articles WHERE id = 7;
我在控制台收到以下输出:
>node run.js
Waiting for database events...
{
type: 'INSERT',
schema: 'test',
table: 'articles',
affectedRows: [ { after: [Object], before: undefined } ],
affectedColumns: [ 'id', 'catid', 'subject', 'content' ],
timestamp: 1701544533000,
nextPosition: 691841809,
binlogName: 'bin.000132'
}
{
type: 'UPDATE',
schema: 'test',
table: 'articles',
affectedRows: [ { after: [Object], before: [Object] } ],
affectedColumns: [ 'subject' ],
timestamp: 1701544536000,
nextPosition: 691842155,
binlogName: 'bin.000132'
}
{
type: 'DELETE',
schema: 'test',
table: 'articles',
affectedRows: [ { after: undefined, before: [Object] } ],
affectedColumns: [ 'id', 'catid', 'subject', 'content' ],
timestamp: 1701544540000,
nextPosition: 691842466,
binlogName: 'bin.000132'
}