Mysql 从机端基于行的主从复制触发事件

Mysql trigger events in a row based master-slave replication on slave-side

我有一个 MySQL 主从数据库和一个从属端的进程,它侦听从属数据库的最新更新并相应地采取行动。我还在从属端写了一个触发器来更新另一个 table (进程正在监听)。

delimiter #
CREATE  TRIGGER on_insert AFTER INSERT ON test
FOR EACH ROW
BEGIN 
    INSERT INTO Ins_table 
    VALUES(NEW.firstname, NEW.id);
end#
delimiter ;

我在从属服务器上插入了触发器(不是在主服务器上,因为我使用的是基于行的复制)。该进程每 10 秒检查一次 "Ins_table" 以获取新记录。复制发生得很好。但是,从属端的触发器永远不会起作用。 我已经在一个单独的数据库中测试了上面的触发器(没有复制),并且它没有任何问题。你能帮我理解为什么插入之后的触发器在基于行的主从复制的从属端不起作用吗?

这是基于行的复制的预期行为,请参阅mysql documentation

Replication and Triggers

With statement-based replication, triggers executed on the master also execute on the slave. With row-based replication, triggers executed on the master do not execute on the slave. Instead, the row changes on the master resulting from trigger execution are replicated and applied on the slave.

This behavior is by design. If under row-based replication the slave applied the triggers as well as the row changes caused by them, the changes would in effect be applied twice on the slave, leading to different data on the master and the slave.

If you want triggers to execute on both the master and the slave—perhaps because you have different triggers on the master and slave—you must use statement-based replication. However, to enable slave-side triggers, it is not necessary to use statement-based replication exclusively. It is sufficient to switch to statement-based replication only for those statements where you want this effect, and to use row-based replication the rest of the time.

请注意,特别是在 MariaDB 中,可以通过启用 slave_run_triggers_for_rbr 来 运行 触发基于行的复制事件。有关 @ https://mariadb.com/kb/en/mariadb/running-triggers-on-the-slave-for-row-based-events/

的更多文档

如果可以选择更改slave 中的复制类型,则可以在slave 中使用mixed,在master 中使用row。使用混合类型将在从机中调用触发器。