阿里云服务器由于不支持keepalive虚拟ip,导致无法通过keepalive来实现mysql的双机热备。我们这里要实现阿里云的双机热备有两种方式:
1,购买阿里云的云数据库高级版,自带从库,主库故障自动切换到从库
2这里主要是讲第二种方式,两台阿里云服务器,分别部署mysql,实现mysql的主主同步。这里就不着重讲mysql的主主同步了,大家可以自行百度,有需要的,以后可能会出一篇文章。假设现在已经实现了mysql主主同步的情况下,如何处理
因为使用的是springboot,所以需要处理下yml文件,然后加了个发送邮件给多个人,这里主机跑的定时任务,备机需要的话,也可以相应的跑一下
因为我是使用docker部署的mysql,所以使用的docker ps 查看mysql的状态,如果普通部署的可以使用ps或者直接登录mysql看能否成功来判断
# coding: utf8
import subprocess
from email.mime.text import MIMEText
import smtplib
import os
#因为这里用的Java的springboot,如果切换备机,需要修改部分yml文件
YML_PATH = ''
NEW_YML = ''
msg_from = '' # 发送方邮箱
passwd = '' # 填入发送方邮箱的授权码
msg_to = []
def check_mysql():
res = subprocess.Popen('docker ps |grep mysql', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = res.communicate()
if stdout:
res_status = subprocess.Popen("docker ps |grep mysql| awk '{print $7}'", stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)
out, err = res_status.communicate()
if out.strip() == "Up":
print 'mysql is ok'
else:
print 'mysql is broken, switch standby machine'
flag = judge_mysql_string()
if flag:
print '已经连接备机,无需切换'
else:
switch_mysql()
else:
print 'mysql is broken, switch standby machine'
flag = judge_mysql_string()
if flag:
print '已经连接备机,无需切换'
else:
switch_mysql()
def switch_mysql():
print '---copy yml----'
subprocess.call('cp {} {}'.format(NEW_YML, YML_PATH), shell=True)
subprocess.call('docker restart tomcat', shell=True)
subject = 'mysql主机故障'
info = 'mysql主机故障,已经切换到备机,请查看主机问题,及时修复,如需切换回去,' \
content = '<html><meta charset="UTF-8"><body><p style="color: red">{}</p> </body></html>'.format(info)
send_email(subject, content)
print '----end switch---'
def send_email(subject, content):
msg = MIMEText(content, 'html', 'utf-8')
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = ','.join(msg_to)
try:
s = smtplib.SMTP_SSL("smtp.qq.com", 465)
s.login(msg_from, passwd)
s.sendmail(msg_from, msg_to, msg.as_string())
except Exception as e:
print e
finally:
s.quit()
def judge_mysql_string():
with open(os.path.join(YML_PATH, 'application.yml'),'r') as f:
res = f.read()
if 'your ip' in res:
return True
else:
return False
check_mysql()