Python程序和MySQL之间的连接丢失

e4eetjau  于 2022-12-17  发布在  Mysql
关注(0)|答案(1)|浏览(302)

为什么会出现此错误?
Mysql.connector.errors.DatabaseError:2003年(HY 000):无法连接到MySQL服务器n '3.XX.XXX.89'(110)
我正在从MQTT代理收集数据并将其存储在MySQL数据库中。为了订阅MQTT代理上的主题,我使用Paho MQTT客户端;为了连接到MySQL数据库服务器,我使用MySQL python连接器。我在Amazon EC2 Ubuntu示例(虚拟服务器)的后台连续运行此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代理。数据是由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服务器的整个时间,而不会导致这个错误?

sqxo8psd

sqxo8psd1#

客户端(比如你的python程序)和MySQL之间的连接在不使用时不会永远保持打开状态,MySQL会在wait_timeoutinteractive_timeout过期时断开连接。
听起来你的程序整天工作,整夜睡觉(就像Monty Python中的伐木工人),当它醒来时,它没有连接到数据库,因为MySQL关闭了它。
你能做些什么呢?按我的喜好排序:
1.更改您的程序以使用connection pool。如果您这样做,池逻辑将在您需要时恢复连接。
1.就在程序处理每个队列项之前,执行一个no-op操作,如SELECT 1;。如果该操作引发异常,则重新打开数据库连接。这是一个很好的解决方案,因为如果MySQL数据库服务器必须重新启动,它会使应用程序更具弹性。(AWS、Azure、Digital Ocean等)不得不让主机停止服务。当他们这样做时,他们会弹出客户虚拟机,这样他们就可以在新的主机上启动。如果你幸运的话,他们会先警告你。
1.更新程序,使其在工作队列变空时关闭数据库连接,并在有工作要做时重新打开。
1.每隔一段时间(一分钟?)执行一次无操作SELECT 1;作为keepalive,这样MySQL就不会关闭连接。
1.将wait_timeout的值更改为足够长的值,将其设置为一周。

SET @@GLOBAL.wait_timeout=604800

使用86400一天。
了解如何设置超时也很有用,因为它使您可以测试此问题的解决方案,而无需等待很长时间。

相关问题