springBoot配置mysql主从,多个从使用
时间: 2023-12-03 18:02:33 浏览: 126
SpringBoot第 12 讲:SpringBoot+MySQL主从复制、读写分离
1. 配置主从复制
在主库中配置:
```yaml
spring.datasource.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# 开启binlog
server-id=1
log-bin=mysql-bin
binlog-format=ROW
```
在从库中配置:
```yaml
spring.datasource.url=jdbc:mysql://localhost:3306/slave1?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# 从库唯一id
server-id=2
# 开启relay log
relay-log=slave1-relay-bin
relay-log-index=slave1-relay-bin.index
```
2. 配置多个从库
在从库中配置:
```yaml
spring.datasource.url=jdbc:mysql://localhost:3306/slave2?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
server-id=3
relay-log=slave2-relay-bin
relay-log-index=slave2-relay-bin.index
```
在主库中配置:
```yaml
# 配置多个从库
# 从库1
server-id=2
log-bin=mysql-bin
binlog-format=ROW
binlog-do-db=slave1
# 从库2
server-id=3
log-bin=mysql-bin
binlog-format=ROW
binlog-do-db=slave2
```
3. 启动主从复制
分别启动主库和从库,然后在从库中执行以下sql语句:
```sql
CHANGE MASTER TO
MASTER_HOST='localhost',
MASTER_PORT=3306,
MASTER_USER='root',
MASTER_PASSWORD='123456',
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=0;
```
其中,`MASTER_HOST`为主库的ip地址,`MASTER_PORT`为主库的端口号,`MASTER_USER`和`MASTER_PASSWORD`为主库的用户名和密码,`MASTER_LOG_FILE`和`MASTER_LOG_POS`为主库的binlog文件名和位置。
执行完毕后,启动从库的复制进程:
```sql
START SLAVE;
```
4. 验证主从复制是否成功
在主库中执行以下sql语句:
```sql
CREATE DATABASE test;
USE test;
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20),
age INT
);
INSERT INTO user (name, age) VALUES ('张三', 20), ('李四', 30);
```
然后在从库中执行以下sql语句:
```sql
USE test;
SELECT * FROM user;
```
如果能够查询到数据,说明主从复制已经成功了。
阅读全文