service mysqld status

只要數據庫服務崩潰了,后面的請求就都會出錯,所以想用一種方法來監控服務器數據庫服務的狀態。自己想了幾種方案,大致分為兩類
1.當有請求到來時,如果發生數據庫連接錯誤,就(通過郵件或者短息)推送信息給管理員,管理員手動去重啟數據庫服務。
2.在系統中設置一個定時任務,每隔一段時間檢查一次數據庫服務狀態,如果服務停了就重啟並通知管理員。
這里介紹的是第二種方法,主要通過shell腳本實現,下面具體說明如何實現。
首先檢測Mysql的狀態
#!/bin/bash
pgrep -x mysqld &> /dev/null
if [ $? -ne 0 ]
then
echo "At time: `date` :MySQL is stop .">> /var/log/mysql_messages
service mysql start
#echo "At time: `date` :MySQL server is stop."
else
echo "MySQL server is running ."
fi
將上述腳本保存到mysql.sh中,上傳到服務器,運行該腳本可以發現輸出數據庫服務正在運行
# sh mysql.sh
MySQL server is running
這里我還出現一個小插曲,就是shell腳本總是運行錯誤,可以參考下面。原來是windows系統和類Unix系統的換行符不一樣。
如果是用sublime編輯器還可以參考
每隔一定時間自動運行腳本
linux上定期執行腳本用的是cron進程
命令:
編輯完畢,按ESC鍵退出,輸入:wq保存后退出。
重啟cron就可以了
使用上面的shell腳本並不會推送數據庫狀態消息給管理員,這里就要借助我以前寫的一篇博客了。
-
crontab -e
輸入(如果不能輸入,按鍵盤上的Insert鍵就能輸入了)
*/5 * * * * /your_dir/mysql.sh
編輯完畢,按ESC鍵退出,輸入:wq保存后退出。
重啟cron就可以了
-
service cron restart
使用上面的shell腳本並不會推送數據庫狀態消息給管理員,這里就要借助我以前寫的一篇博客了。
Centos7-mqtt消息中間件mosquitto的安裝和配置
借助mosquitto服務可以將消息推送到管理員客戶端。
#!/bin/bash
pgrep -x mysqld &> /dev/null
if [ $? -ne 0 ]
then
mosquitto_pub -t mysql_status -m "Failed"
service mysql start
#echo "At time: `date` :MySQL server is stop."
else
mosquitto_pub -t mysql_status -m "Running"
fi
服務器發布主題為“mysql_status”的消息,再使用客戶端來接收該消息。
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("mysql_status")
#訂閱,第一個參數是訂閱的主題
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("主機名或ip", 1883, 60)
#第一個參數為主機名,及Mosquitto所在服務器,第二個參數是端口
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

參考: