PyMySQL == 0.7.11,MySQL服务器已经消失[重复]

Posted

技术标签:

【中文标题】PyMySQL == 0.7.11,MySQL服务器已经消失[重复]【英文标题】:PyMySQL==0.7.11, MySQL server has gone away [duplicate] 【发布时间】:2019-08-31 13:11:13 【问题描述】:

我有一个基于 Python Tornado 框架编写的应用程序。

我编写了一个脚本,通过隧道侦听消息,当满足我的条件时,脚本连接到 mysql 并执行插入或更新,但经过很长时间我收到 MySQL 已断开连接的错误。

听隧道我使用 pika 模块。所以当一切都发生时,我得到了这个

Pika: Could not connect to host 127.0.0.1 on port 5671

MySQL: (2006, "MySQL server has gone away (ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))")

我的代码如下:

import pika

def main():
    credentials = pika.PlainCredentials('user', 'password')

    try:
        cp = pika.ConnectionParameters(
            host='127.0.0.1',
            port=5671,
            credentials=credentials,
            ssl=False,
        )

        connection = pika.BlockingConnection(cp)
        channel = connection.channel()

        def callback(ch, method, properties, body):
            if 'messageType' in properties.headers:
                message_type = properties.headers['messageType']
                if message_type in allowed_message_types:
                    result = proto_file._reflection.ParseMessage(descriptors[message_type], body)
                    if result:
                        result = protobuf_to_dict(result)
                        if message_type == '1':
                            Model.message_event(data=result)


                else:
                    print('Message type not in allowed list = ' + str(message_type))
                    print('continue listening...')

        channel.basic_consume(callback, queue='queue', no_ack=True)

        print(' [*] Waiting for messages. To exit press CTRL+C')
        channel.start_consuming()
    except Exception as e:
        print('Could not connect to host 127.0.0.1 on port 5671')
        print(str(e))

这是连接到 MySQL 的 message_event 模型

import pymysql
import pymysql.cursors


class Model(object):
    def __init__(self, conf):
        self.conf = conf
        conv = pymysql.converters.conversions.copy()
        conv[246] = Decimal
        conv[10] = str

        self.mysql = pymysql.connect(
            host=self.conf['host'],
            user=self.conf['user'],
            password=self.conf['password'],
            db=self.conf['db'],
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor,
            autocommit=self.conf['autocommit'],
            conv=conv)


    def message_event(self, data):
        with self.mysql.cursor() as cursor:
            // here doing following operations
            // select, insert or update
            cursor.close()

    // and after sometime i get this
    Pika: Could not connect to host 127.0.0.1 on port 5671
    MySQL: (2006, "MySQL server has gone away (ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))")

主要点一旦连接到隧道,必须无限监听消息并在MySQL内部对消息进行操作,但一段时间后连接丢失。

如果可能的话,不更改 MySQL 服务器的配置,将不胜感激任何解决此问题的想法。

【问题讨论】:

【参考方案1】:

我想发布我的有效答案,只有这个解决方案对我有效

    连接mysql前检查连接是否打开,如果没有重新连接

    if not self.mysql.open:
        self.mysql.ping(reconnect=True)
    

【讨论】:

以上是关于PyMySQL == 0.7.11,MySQL服务器已经消失[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Python学习笔记-pyMySQL连接MySQL数据库

在windows下MySQL-python的安装

Python/MySQL(pymysql使用)

PyMySQL 与 Django,多线程应用程序

mysql用户管理+pymysql模块

pymysql