gpt4 book ai didi

mysql - PyMySQL==0.7.11,MySQL服务器消失了

转载 作者:行者123 更新时间:2023-11-29 06:32:18 25 4
gpt4 key购买 nike

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

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

听隧道我使用鼠兔模块。所以当一切发生时我明白了

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)

关于mysql - PyMySQL==0.7.11,MySQL服务器消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55606405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com