为什么会出现这个错误?
Mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server n '3.XX.XXX.89' (110)
我正在从MQTT broker收集数据并将其存储在MySQL数据库中。为了订阅MQTT broker的主题,我使用Paho MQTT客户端,为了连接MySQL数据库服务器,我使用MySQL python连接器。
import mysql.connector
import paho.mqtt.client as mqtt
#Mysql Settings
db = mysql.connector.connect(host='localhost',
user='user_name',
password='password',
db='db_name')
if db.is_connected():
db_Info = db.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = db.cursor()
#MQTT Settings
MQTT_Broker = "3.XX.XXX.89"
MQTT_Port = 1883
Keep_Alive_Interval = 60
MQTT_Topic = "my/publish/#"
#Subscribe
def on_connect(client, userdata, flags, rc):
mqttc.subscribe(MQTT_Topic, 0)
print("subscribed")
#Save data into DB Table
def on_message(mosq, obj, msg):
print("Insert from MQTT")
print("wait")
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
sql = """INSERT INTO gnss (topic, gnssdata) VALUES (%s,%s)"""
tuple = (msg.topic, msg.payload)
cursor.execute(sql, tuple)
db.commit()
print("Record inserted successfully into gnss table")
def on_subscribe(mosq, obj, mid, granted_qos):
pass
mqttc = mqtt.Client()
#Assign Event Callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
#Connect
mqttc.connect(MQTT_Broker, int(MQTT_Port), int(Keep_Alive_Interval))
#Continue the network loop and close db connection
mqttc.loop_forever()
db.close()
print("MySQL connection is closed")
在这个虚拟服务器上安装了Mosquitto for mqtt和mysql server.首先当我运行这个脚本时,所有来自MQTT broker的数据都被收集并存储到mysql数据库中。这一天的工作都很正常。第二天,在没有做任何修改的情况下,我向MQTT broker发送了数据。这些数据被paho mqtt客户端收集,但它无法将这些数据存储在mysql数据库中,错误和输出如下。
('Connected to MySQL Server version ', '5.7.30-0ubuntu0.18.04.1')
subscribed
Insert from MQTT
wait
my/publish/topic 0 acc, 10245, tyu
Record inserted successfully into gnss table
Insert from MQTT
wait
my/publish/topic 0 hello world
Record inserted successfully into gnss table
Insert from MQTT
wait
my/publish/topic 0 hello world
Record inserted successfully into gnss table
Insert from MQTT
wait
my/publish/topic 0 new test
Record inserted successfully into gnss table
Insert from MQTT
wait
my/publish/topic 0 19/05/2020
Insert from MQTT
wait
my/publish/topic 0 19/05/2020
Insert from MQTT
wait
my/publish/topic 0 Tuesday
Insert from MQTT
wait
my/publish/topic 0 Tuesday
Traceback (most recent call last):
File "mqtt.py", line 8, in <module>
db='nrf91')
File "/home/ubuntu/.local/lib/python2.7/site-packages/mysql/connector/__init__.py", line 264, in connect
return CMySQLConnection(*args, **kwargs)
File "/home/ubuntu/.local/lib/python2.7/site-packages/mysql/connector/connection_cext.py", line 80, in __init__
self.connect(**kwargs)
File "/home/ubuntu/.local/lib/python2.7/site-packages/mysql/connector/abstracts.py", line 960, in connect
self._open_connection()
File "/home/ubuntu/.local/lib/python2.7/site-packages/mysql/connector/connection_cext.py", line 219, in _open_connection
sqlstate=exc.sqlstate)
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '3.XX.XXX.89' (110)
我得到这个mysql连接器数据库错误。如何解决这个错误?最初有连接到mysql服务器,但第二天就没有了。那么如何让它一直连接到mysql服务器上,而不引起这个错误呢?
客户端(比如你的python程序)和MySQL之间的连接在不使用时不会永远保持开放。 MySQL会在其 wait_timeout
或 interactive_timeout
,过期作废。
听起来你的程序整天工作,整夜睡觉(就像Monty Python笑话里的伐木工)。当它醒来时,它没有连接到数据库,因为MySQL关闭了它。
你能对这个问题做什么?按照我的喜好顺序。
在你的程序处理每一个排队的项目之前,执行一个无操作的操作,比如说 SELECT 1;
. 如果该操作抛出异常,则重新打开数据库连接。这是一个很好的解决方案,因为如果MySQL数据库服务器必须重新启动,它使你的应用程序更具弹性。有时,云提供商(AWS、Azure、Digital Ocean等)不得不将主机退出服务。当他们这样做时,他们会弹出客户的虚拟机,以便他们可以在新的主机上启动。如果你很幸运,他们会先警告你。
更新你的程序,使它在工作队列变空时关闭数据库连接,并在有工作要做时重新打开它。
每隔一段时间(一分钟?)做一次no-op。SELECT 1;
作为一个keepalive,这样MySQL就不会关闭连接。
改变 wait_timeout
值到足够长的东西。这将其设置为一周。
SET @@GLOBAL.wait_timeout=604800
使用 86400
一天的时间。
知道如何设置超时也很有用,因为它可以让你测试你对这个问题的解决方案,而不需要等待很长时间。