【mysql】【binlog】mysql配置binlog

时间:2025-03-30 14:15:53

Mysql如何配置BinLog

注意:

建议配置进行cdc同步的数据库为从库而非日常进行增删改查的主库;若只能使用主库进行cdc同步的话,则建议降低同步速率,减小对DML操作的影响。

Linux环境

  1. 修改
log_bin = MYON // 任意名称均可,只要配置了名称即开启binlog
server-id = 123 // 配置与其它server不同的id
binlog-format = row // 设置binlog模式为row

// ------------可选配置项
binlog_ignore_db = *** //指定不记录二进制日志的数据库
binlog_do_db = *** //明确指定要记录日志的数据库
log_bin_index = *** //指定文件的路径
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 重启mysql
  2. 进入mysql修改binlog_row_image为full
set global binlog_row_image="full";
  • 1
  1. 查看binlog开启是否生效
show variables like '%log_bin%';(需要设置为ON)
  • 1
  1. 查看binlog模式和binlog_row_image配置
show global variables like '%binlog_format%';(需要设置为ROW模式)
show variables like '%binlog_row_image%';(需要设置为FULL)
  • 1
  • 2
  1. 创建用户和赋权
> create user 'dp_test'@'%' identified by '12345678';
> grant SELECT on mysql.db to 'dp_test'@'%';
> grant SELECT on mysql.tables_priv to 'dp_test'@'%';
> grant SELECT on mysql.user to 'dp_test'@'%';
> grant SELECT on test.* to 'dp_test'@'%';
> grant LOCK TABLES on test.* to 'dp_test'@'%';
> GRANT SELECT, RELOAD, SHOW DATABASES, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'dp_test' IDENTIFIED BY '12345678';
> flush privileges;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Windows环境

windows环境下的binlog配置除了修改的文件不一致(linux为文件,windows为my.ini文件),其余操作均相同。

  1. 修改文件
log_bin = MYON // 任意名称均可,只要配置了名称即开启binlog
server-id = 123 // 配置与其它server不同的id
binlog-format = row // 设置binlog模式为row
  • 1
  • 2
  • 3

(其余操作均与linux环境下的配置相同,此处省略)

mysql配置主库从库

  1. 搭建两个数据库,并设置各自的数据存放目录
  2. 将其中一个数据库作为master主库,在master 文件中配置
[mysqld]
server_id = 1
log-bin= mysql-bin # 开启binlog
read-only=0 # 主库支持修改
replicate-ignore-db=mysql # 不备份的数据库
replicate-ignore-db=sys
replicate-ignore-db=information_schema  # 备份的数据库
replicate-ignore-db=performance_schema
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 另一个数据库作为slave从库,在slave 文件中配置
[mysqld]
server_id = 2
log-bin= mysql-bin
read-only=1 # 从库read-only
# 备份数据库设置需与主库一致
replicate-ignore-db=mysql
replicate-ignore-db=sys
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. 在master数据库中创建用户同步数据,每个slave使用标准的MySQL用户名和密码连接master。进行复制操作的用户会授予REPLICATION SLAVE 权限。
CREATE USER 'slave'@ '%' IDENTIFIED BY '123456'; GRANT REPLICATION SLAVE ON *.* to 'slave'@'%' identified by '123456';
# 查看状态,记住file、position的值
show master status;
  • 1
  • 2
  • 3
  1. 在slave数据库中设置主库连接并启动同步。
# 设置主库链接
change master to master_host='(主库ip)',master_user='slave',master_password='123456',master_log_file='主库状态的file值',master_log_pos='主库状态的position',master_port=3306;
# 启动从库同步
start slave;
# 查看状态
show slave status;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

如果主库和从库的status都为yes,则配置成功。

注意事项

在主从没有生效的时候,要保持两台服务器数据库、表相同,数据相同。

来源参考:/jinjiangongzuoshi/p/
官网指引:/watch?v=N3tFISmtn7A