python - Gearman + SQLAlchemy - 不断丢失 MySQL 线程

标签 python mysql sqlalchemy pylons gearman

我有一个 python 脚本,可以设置几个 gearman worker。他们在我拥有的 SQLAlchemy 模型上调用了一些方法,这些方法也被 Pylons 应用程序使用。

在一两个小时内一切正常,然后 MySQL 线程丢失并且所有查询失败。当我为 pool_recycle 定义如此低的值时,我无法弄清楚为什么线程会丢失(我在 3 个不同的服务器上得到相同的结果)。另外,为什么不创建新连接?

有什么要调查的想法吗?

import gearman
import json
import ConfigParser
import sys
from sqlalchemy import create_engine

class JSONDataEncoder(gearman.DataEncoder):
    @classmethod
    def encode(cls, encodable_object):
        return json.dumps(encodable_object)
    @classmethod
    def decode(cls, decodable_string):
        return json.loads(decodable_string)

# get the ini path and load the gearman server ips:ports
try:
    ini_file = sys.argv[1]
    lib_path = sys.argv[2]
except Exception:
    raise Exception("ini file path or anypy lib path not set")

# get the config
config = ConfigParser.ConfigParser()
config.read(ini_file)
sqlachemy_url =  config.get('app:main', 'sqlalchemy.url')
gearman_servers =  config.get('app:main', 'gearman.mysql_servers').split(",")

# add anypy include path
sys.path.append(lib_path)
from mypylonsapp.model.user import User, init_model
from mypylonsapp.model.gearman import task_rates

# sqlalchemy setup, recycle connection every hour
engine = create_engine(sqlachemy_url, pool_recycle=3600)
init_model(engine)

# Gearman Worker Setup
gm_worker = gearman.GearmanWorker(gearman_servers)
gm_worker.data_encoder = JSONDataEncoder()

# register the workers
gm_worker.register_task('login', User.login_gearman_worker)
gm_worker.register_task('rates', task_rates)

# work
gm_worker.work()

最佳答案

我已经在 Ruby、PHP 和 Python 中全面看到了这一点,而不管使用的数据库库是什么。我找不到如何以使用 mysql_ping 的“正确”方式解决这个问题,但是有一个 SQLAlchemy 解决方案,这里有更好的解释 http://groups.google.com/group/sqlalchemy/browse_thread/thread/9412808e695168ea/c31f5c967c135be0

正如该线程中有人指出的那样,将回收选项设置为等于 True 等同于将其设置为 1。更好的解决方案可能是找到您的 MySQL 连接超时值并将回收阈值设置为它的 80%。

您可以通过查找此变量 http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_connect_timeout 从实时集合中获取该值

编辑: 我花了一点时间找到有关使用 pool_recycle 的权威文档 http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/connections.html?highlight=pool_recycle

关于python - Gearman + SQLAlchemy - 不断丢失 MySQL 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4890927/

相关文章:

python - 手动调用带参数的装饰器

python - 如何在Python中找到列表中单词最多的句子?

mysql - 数据库设计-两个相等对象的属性

python - 将 SQLalchemy 与 gevent 一起使用是否安全?

python - 用户输入中的可选参数

php - 如何使用 PHP 从 MySQL 数据库生成整个数据库表的 JSON 数组

php mysql 错误 - #1273 - #1273 - 未知排序规则 : 'utf8mb4_general_ci'

postgresql - 用于数据库连接的 Flask before_request 和 teardown_request

python - 使用python sqlalchemy,如何定义多列主键

python - git-pylint-commit-hook 不检查所有项目文件