在CentOS上配置MySQL读写分离可以通过多种方式实现,其中一种常见的方法是使用MySQL复制(Replication)和应用程序逻辑或代理工具。以下是一个基本的步骤指南,使用MySQL复制和MaxScale作为代理工具来实现读写分离。
安装MySQL主服务器和从服务器:
sudo yum install mysql-server
sudo systemctl start mysqld
sudo systemctl enable mysqld
配置MySQL复制:
/etc/my.cnf或/etc/mysql/my.cnf,添加以下配置:[mysqld]
server-id=1
log_bin=mysql-bin
auto_increment_increment=2
auto_increment_offset=1
/etc/my.cnf或/etc/mysql/my.cnf,添加以下配置:[mysqld]
server-id=2
relay_log=mysql-relay-bin
log_bin=mysql-bin
read_only=1
auto_increment_increment=2
auto_increment_offset=2
重启MySQL服务:
sudo systemctl restart mysqld
在主服务器上创建复制用户:
CREATE USER 'replicator'@'%' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%';
FLUSH PRIVILEGES;
获取主服务器的二进制日志位置:
SHOW MASTER STATUS;
记录File和Position的值。
在从服务器上配置复制:
CHANGE MASTER TO
MASTER_HOST='master_ip',
MASTER_USER='replicator',
MASTER_PASSWORD='password',
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=123;
START SLAVE;
下载并安装MaxScale:
sudo yum install maxscale
配置MaxScale:
编辑/etc/maxscale.cnf,添加以下配置:
[MAXSCALE]
threads=4
daemon=on
[MySQL-Reader]
type=service
router=readwritesplitting
servers=slave_ip:3306
user=maxscale
password=maxscale_password
[MySQL-Writer]
type=service
router=writer
servers=master_ip:3306
user=maxscale
password=maxscale_password
[ServerPool-Writer]
type=serverpool
address=master_ip:3306
scheduler=least_connections
[ServerPool-Reader]
type=serverpool
address=slave_ip:3306
scheduler=least_connections
[Listener-MySQL]
type=listener
service=MySQL-Reader
protocol=MySQLClient
module=maxscale_socket
host=0.0.0.0
port=3306
启动MaxScale:
sudo systemctl start maxscale
连接到MaxScale:
mysql -u maxscale -p -h localhost -P 3306
检查MaxScale状态:
SELECT * FROM maxscale.get_services();
通过以上步骤,你可以在CentOS上配置MySQL读写分离。请注意,这只是一个基本的示例,实际生产环境中可能需要更复杂的配置和监控。