Configuring MySQL Read-Write Separation Tutorial

Configuring MySQL read-write separation is a common database architecture method, which can distribute read requests and write requests to different MySQL instances to improve database performance and scalability. Here's a user-friendly step-by-step guide:

  1. Deploy the master database (Master) and at least one slave database (Slave). Make sure all database instances have MySQL installed and running properly.
  2. Make configuration changes on the primary database. Edit the MySQL configuration file (usually  my.cnf), find the following lines and change accordingly:

    server-id = 1
    log_bin = /var/log/mysql/mysql-bin.log
    binlog_do_db = your_database_name

    These configurations will enable the binary log (binary log), and specify the database to be replicated.

  3. Restart the master database for the configuration changes to take effect:

    sudo service mysql restart
  4. Make configuration changes on the slave database. Edit the MySQL configuration file, find the following lines and change accordingly:

    server-id = 2
    relay_log = /var/log/mysql/mysql-relay-bin.log
    read_only = 1

    These configurations will enable the relay log and set the slave database to read-only mode.

  5. Restart the slave database for configuration changes to take effect:

    sudo service mysql restart
  6. Create a MySQL user for replication on the master database and grant the user replication privileges:

    CREATE USER 'replication_user'@'slave_ip_address' IDENTIFIED BY 'password';
    GRANT REPLICATION SLAVE ON *.* TO 'replication_user'@'slave_ip_address';
    FLUSH PRIVILEGES;

    Will  slave_ip_addressbe replaced by the IP address of the slave database passwordand the password of the user.

  7. Configure replication on the slave database. Connect to the MySQL instance of the slave database and execute the following command:

    STOP SLAVE;
    CHANGE MASTER TO MASTER_HOST='master_ip_address', MASTER_USER='replication_user', MASTER_PASSWORD='password';
    START SLAVE;

    Replace  master_ip_addressthe IP address of the primary database passwordwith the password of the replication user.

  8. Make sure the slave database is successfully connected to the master database and start replication. The replication status can be checked with the following command:

    SHOW SLAVE STATUS\G

Through the above steps, you can configure MySQL read-write separation. At this point, the write request can be sent to the master database, and the read request can be sent to any slave database, thereby sharing the load of the master database and improving the performance and scalability of the database. Note that during configuration, be careful with sensitive information (such as passwords) and ensure that the network connectivity and security settings between DB instances are correct.

Guess you like

Origin blog.csdn.net/tiansyun/article/details/132126885