MySQL主从


一、mysql 主从

介绍

MySQL主从复制是一种常见的数据库复制技术,可以将一个MySQL数据库的数据复制到多个从库中,从而提高读取性能和数据可用性。

在主从复制中,主库是数据的源头,从库是数据的副本,主库将数据变更记录到二进制日志中,从库通过读取二进制日志实现数据的同步。

MySQL主从复制技术的主要作用是提高MySQL数据库的读取性能和数据可用性。

具体来说,主从复制可以实现以下几个方面的作用:

  1. 读写分离:主库负责处理写操作,从库负责处理读操作,从而分担主库的读取压力,提高数据库的读取性能。
  2. 数据备份:通过将主库的数据同步到从库中,可以实现数据的备份和恢复,保证数据的可用性和安全性。
  3. 故障切换:当主库出现故障时,可以通过将从库切换为主库,保证数据库的正常访问。
  4. 负载均衡:通过将多个从库连接到主库,可以实现负载均衡,提高数据库的处理能力和并发性能。
  5. 数据分析:可以使用从库作为数据分析的副本,避免对主库造成影响,提高数据分析的效率。

相比redis主从,mysql主从的原理相对复杂一些

image

# mysql 主从原理
步骤一:主库db的更新事件(update、insert、delete)被写到binlog
步骤二:从库发起连接,连接到主库
步骤三:此时主库创建一个binlog dump thread线程,把binlog的内容发送到从库
步骤四:从库启动之后,创建一个I/O线程,读取主库传过来的binlog内容并写入到relay log.
步骤五:还会创建一个SQL线程,从relay log里面读取内容,从Exec_Master_Log_Pos位置开始执行读取到的更新事件,将更新内容写入到slave的db.

搭建步骤

# 搭建步骤 :准备两台机器 (mysql的docker镜像模拟两台机器)
	-主库:10.0.0.102 33307
    -从库:10.0.0.102 33306

    
    # 第一步:拉取mysql5.7的镜像
    # 第二步:创建文件夹,文件(目录映射)
        mkdir /home/mysql
        mkdir /home/mysql/conf.d
        mkdir /home/mysql/data/
        touch /home/mysql/my.cnf
        
        mkdir /home/mysql1
        mkdir /home/mysql1/conf.d
        mkdir /home/mysql1/data/
        touch /home/mysql1/my.cnf

    # 第三步(重要):编写mysql配置文件(主,从)
    #### 主的配置####
    [mysqld]
    user=mysql
    character-set-server=utf8
    default_authentication_plugin=mysql_native_password
    secure_file_priv=/var/lib/mysql
    expire_logs_days=7
    sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
    max_connections=1000
    server-id=100
    log-bin=mysql-bin
    [client]
    default-character-set=utf8

    [mysql]
    default-character-set=utf8



    #### 从库的配置#####
    [mysqld]
    user=mysql
    character-set-server=utf8
    default_authentication_plugin=mysql_native_password
    secure_file_priv=/var/lib/mysql
    expire_logs_days=7
    sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
    max_connections=1000
    server-id=101  
    log-bin=mysql-slave-bin   
    relay_log=edu-mysql-relay-bin 

    [client]
    default-character-set=utf8

    [mysql]
    default-character-set=utf8
    
    
	#第三步:启动mysql容器,并做端口和目录映射
	docker run  -di -v /home/mysql/data/:/var/lib/mysql -v /home/mysql/conf.d:/etc/mysql/conf.d -v /home/mysql/my.cnf:/etc/mysql/my.cnf -p 33307:3306 --name mysql-master -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7


   docker run  -di -v /home/mysql1/data/:/var/lib/mysql -v /home/mysql1/conf.d:/etc/mysql/conf.d -v /home/mysql1/my.cnf:/etc/mysql/my.cnf -p 33306:3306 --name mysql-slave -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7

                    
   #第四步:连接主库
	mysql -uroot -P33307 -h 10.0.0.102 -p
    #在主库创建用户并授权
    ##创建test用户
    create user 'test'@'%' identified by '123';
    ##授权用户
    grant all privileges on *.* to 'test'@'%' ;
    ###刷新权限
    flush privileges;
    #查看主服务器状态(显示如下图)
    show master status; 

   # 第五步:连接从库
	mysql -uroot -P33306 -h 10.0.0.102 -p
    #配置详解
    '''
    change master to 
    master_host='MySQL主服务器IP地址', 
    master_user='之前在MySQL主服务器上面创建的用户名', 
    master_password='之前创建的密码', 
    master_log_file='MySQL主服务器状态中的二进制文件名', 
    master_log_pos='MySQL主服务器状态中的position值';
    '''
    change master to master_host='10.0.0.102',master_port=33307,master_user='test',master_password='123',master_log_file='mysql-bin.000003',master_log_pos=0;
    #启用从库
    start slave;
    #查看从库状态(如下图)
    show slave status\G;
    
    
    
    # 第六版:在主库创建库,创建表,插入数据,看从库

image

image

二、django使用多数据库做读写分离

步骤一

在配置文件中配置多数据库

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    },
    'db1': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db1.sqlite3',
    }
}

步骤二

手动实现数据库读写分离

Book.objects.using('db1').create(name='西游记')

ps:我们在执行数据库迁移的时候可以指定迁移到哪个数据库,如果不具体写上参数,就会迁移到default对应的数据库中

python manage.py migrate --database=db1

步骤三

配置自动读写分离

创建一个py文件,db_router.py,写一个类:

class DBRouter(object):
    def db_for_read(self, model, **hints):
        # 多个从库 ['db1','db2','db3']
        return 'db1'

    def db_for_write(self, model, **hints):


        return 'default'

步骤四

在配置文件中配置

DATABASE_ROUTERS = ['mysql_master_demo.db_router.DBRouter', ]

这样配置后,就实现了自动读写分离


posted @   致丶幻  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
  1. 1 So Far Away (Acoustic) Adam Christopher
  2. 2 雪 Distance Capper&罗言RollFlash
  3. 3 CollapsingWorld
  4. 4 Call You Tonight Johnta Austin
So Far Away (Acoustic) - Adam Christopher
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作曲 : David Guetta/Giorgio H Tuinfort/Jamie Scott/Martijn G Garritsen

Light ‘em up, light ‘em up

Tell me where you are, tell me where you are

The summer nights, the bright lights

And the shooting stars, they break my heart

I‘m calling you now, but you‘re not picking up

Your shadows so close if you are still in love

Then light a match, light a match

Baby, in the dark, show me where you are

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day and now you‘re so far away

It‘s breaking me, I‘m losing you

We were far from perfect, but we were worth it

Too many fights, and we cried, but never said we‘re sorry

Stop saying you love me

You‘re calling me now, but I can‘t pick up

Your shadow‘s too close, and I‘m still in love

The summer‘s over now, but somehow, it still breaks my heart

We could have had the stars, oh

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day and now you‘re so far away

Oh, love

How I miss you every single day when I see you on those streets

Oh, love

Tell me there‘s a river I can swim that will bring you back to me

‘Cause I don‘t know how to love someone else

I don‘t know how to forget your face

Oh, love

God, I miss you every single day when you‘re so far away

点击右上角即可分享
微信分享提示